C# 在ASP.NET MVC中查看覆盖模型数据的数据字典
我有一个创建用户的视图,如下所示C# 在ASP.NET MVC中查看覆盖模型数据的数据字典,c#,asp.net-mvc,html-helper,C#,Asp.net Mvc,Html Helper,我有一个创建用户的视图,如下所示 <% using (Html.BeginForm("SaveUser", "Security")) {%> <p> <label for="UserName">UserName:</label> <%= Html.TextBox("UserName") %> <%= Html.ValidationMessage("UserName", "*"
<% using (Html.BeginForm("SaveUser", "Security")) {%>
<p>
<label for="UserName">UserName:</label>
<%= Html.TextBox("UserName") %>
<%= Html.ValidationMessage("UserName", "*") %>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.TextBox("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<input type="submit" value="Create" />
</p>
<}%>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveUser( UserViewModel user)
{
//user.Id is zero before save
//Save the user. Code omitted...
//user.Id is now greater than zero
//redirect to edit user view
return View("EditUser", user );
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveUser( UserViewModel user)
{
//user.Id is zero before save
//Save the user. Code omitted...
//user.Id is now greater than zero
//clear the view data
ViewData = new ViewDataDictionary();
//redirect to edit user view
return View( "EditUser", user);
}
保存用户后,页面将重定向到带有
<p>
<label for="Id">Id:</label>
<%= Html.Hidden("Id", Model.Id)%>
</p>
果然,这起作用了。隐藏字段现在具有正确用户ID的值
我们找到了治疗症状的方法,但问题的根源在哪里?
我不喜欢每次在返回另一个视图之前清除视图数据字典的想法。操作成功后,您应该使用
return RedirectToAction("EditUser", new { id = user.Id });
或类似代码。当前模型状态用于生成视图,而模型绑定器未绑定Id
[Bind(Exclude=“Id”)]
也可以工作,但是重定向会创建新页面(不使用当前的ModelState),这是一个更好的解决方案
编辑:
如果您不想绑定整个对象,您应该使用
[bind(Exclude)]
或者您应该将SaveUser
定义为SaveUser(字符串用户名、字符串密码)
并自己构建UserViewModel
对象。这将避免模型绑定器和模型值产生的错误,您不知道这些错误来自何处。操作成功后,您应该使用
return RedirectToAction("EditUser", new { id = user.Id });
或类似代码。当前模型状态用于生成视图,而模型绑定器未绑定Id
[Bind(Exclude=“Id”)]
也可以工作,但是重定向会创建新页面(不使用当前的ModelState),这是一个更好的解决方案
编辑:
如果您不想绑定整个对象,您应该使用
[bind(Exclude)]
或者您应该将SaveUser
定义为SaveUser(字符串用户名、字符串密码)
并自己构建UserViewModel
对象。这将避免模型绑定器和模型值产生的错误,您不知道这些错误来自何处。++,这是处理此问题的首选方法。它还解决了用户刷新页面并无意中重新发布同一表单帖子的问题。根据系统的不同,如果你的动作不是幂等的,那可能是件坏事。@LukLed,@Joel:谢谢大家的帮助。我的UserViewModel比我在这里发布的更复杂,所以我编写了自定义模型活页夹。我的一个朋友找到了一种不用自定义活页夹而使用默认活页夹的方法,因此我将努力切换到该活页夹。@LukLed:使用RedirectToAction后,问题仍然存在,我不得不使用ViewData=new ViewDataDictionary();换句话说,使用重定向并不能解决问题。有什么我遗漏的吗?++,这是最好的处理方法。它还解决了用户刷新页面并无意中重新发布同一表单帖子的问题。根据系统的不同,如果你的动作不是幂等的,那可能是件坏事。@LukLed,@Joel:谢谢大家的帮助。我的UserViewModel比我在这里发布的更复杂,所以我编写了自定义模型活页夹。我的一个朋友找到了一种不用自定义活页夹而使用默认活页夹的方法,因此我将努力切换到该活页夹。@LukLed:使用RedirectToAction后,问题仍然存在,我不得不使用ViewData=new ViewDataDictionary();换句话说,使用重定向并不能解决问题。有什么我遗漏的吗?