Asp.net mvc 将Html.TextBox值设置为null
我在MVC视图上有以下文本框:Asp.net mvc 将Html.TextBox值设置为null,asp.net-mvc,Asp.net Mvc,我在MVC视图上有以下文本框: @Html.TextBoxFor(x => x.Captcha, new { @value = "" }) 我正在尝试文本框始终是空的,当表单显示后提交错误。。。但这是行不通的。我总是看到最后一个值 这是我的控制器: [Route("signup"), HttpGet] public virtual ActionResult SignUp() { UserSignUpModel model = new UserSignUpModel(); mod
@Html.TextBoxFor(x => x.Captcha, new { @value = "" })
我正在尝试文本框始终是空的,当表单显示后提交错误。。。但这是行不通的。我总是看到最后一个值
这是我的控制器:
[Route("signup"), HttpGet]
public virtual ActionResult SignUp() {
UserSignUpModel model = new UserSignUpModel();
model.Captcha = String.Empty;
model.Email = "";
return View(model);
} // SignUp
[Route("signup"), HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult SignUp(UserSignUpModel model) {
if (ModelState.IsValid) {
// Create account code
return View(MVC.Shared.Views._Note, new NoteModel("Account created"));
} else {
model.Captcha = String.Empty;
model.Email = "";
return View(Views.SignUp, model);
}
}
谢谢,,
Miguel在控制器的操作方法中手动设置此参数:
// ...
model.Captcha = String.Empty;
return View(model);
我建议将autocomplete=off html属性添加到您的验证码字段:
@Html.TextBoxFor(x => x.Captcha, new { autocomplete = "off" })
如果表单提交时有错误,只需在返回有错误的视图之前清除ViewData并在控制器中显式清除属性即可
[HttpPost]
public ActionResult MyController(Model myModel)
{
if (!ModelState.IsValid)
{
myModel.Captcha = String.Empty;
ViewData = null;
return View(myModel);
}
return View(myModel);
}
我能解决这个问题。正确的方法是使用模型状态: ModelState[“Captcha”]。Value=new ValueProviderResult(“,”,Thread.CurrentThread.CurrentCulture) 这样就不需要清除ViewData中的其他数据
通过更改ModelState,而不是删除它,仍然可以显示与该属性相关的错误。我添加了您的两个建议,而不是运气。。。很奇怪,当我使用model.Captcha=String.Empty;现在看来。。。知道吗?我刚用控制器代码更新了我的帖子。。。我还尝试将电子邮件设置为“”,结果相同。使用HttpContext.Request.Params[“Captcha”]=“我得到:System.dll中发生了类型为“System.NotSupportedException”的异常,但未在用户代码中处理其他信息:集合为只读。是的!这是因为ViewData!Asp.Net对开发人员隐藏了太多信息,所以有时候真的很困惑,因为我们不能按照您的建议去做。。。当我使用ViewData=null时,我能够使Captcha=“”,但我在ViewBag上的数据被删除。还有其他选择吗?你能粘贴你的用户注册模型吗?