我想用强类型视图实现我的编辑操作方法,它接收自定义形状的ViewModel类。换句话说,我需要一个强类型的ViewModel,它包含应该被编辑的Linq实体以及应该在视图中显示的其他一些对象。在POST操作方法中强类型ViewModel只包含空值
我可以在调用GET Edit操作方法时看到视图,但强类型的POST操作方法仅接收一个带有空参数的ViewModel类,我无法弄清楚如何检索POST参数。
视图模型如下所示:
//my custom-shaped ViewModel
public class CustomersFormViewModel
{
public SelectList AccountTypesDropDownBox;
public SelectList CountriesDropDownBox;
public Customer Customer;
}
的操作方法如下所示:
//
// GET: /CustomersController/Edit
public ActionResult Edit(int ID)
{
var model = new CustomersFormViewModel
{
Customer = repository.Load(ID.Value),
CountriesDropDownBox = GetCountries(),
AccountTypesDropDownBox = GetAccountTypes()
};
return View(model);
}
//
// POST: /CustomersController/Edit
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(CustomersFormViewModel model)
{
//THE NEXT LINE THROWS!!!
Debug.Assert(Model.Customer!=null);
return View(model);
}
这是我编辑观点:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/CustAdminMaster.master"
Inherits="System.Web.Mvc.ViewPage<Zeiterfassung.Controllers.CustomersController+CustomersFormViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
NewEdit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
NewEdit</h2>
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm())
{%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="FirstName">FirstName:</label>
<%= Html.TextBox("FirstName",Model.Customer.FirstName) %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
我也尝试使用formValues参数的POST操作方法,但视图模型仍不包含发布的参数:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int ID, FormCollection formValues)
{
CustomersFormViewModel model = new CustomersFormViewModel();
UpdateModel(model);
//THE NEXT LINE STILL THROWS
Debug.Assert(model.Customer!=null);
return View("NewEdit",model);
}
到目前为止,我已经找到了唯一的办法就是写我自己的代码,抓住从的FormCollection张贴的参数,并更新我的自定义视图模型相应。但是这种方法似乎有点原始。有没有更好的方法来做到这一点?
编辑:我只是试着视图中的不同的语法tvanfosson建议,但问题仍然不变:
<label for="Customer.FirstName">FirstName:</label>
<%= Html.TextBox("Customer.FirstName") %>
<%= Html.ValidationMessage("Customer.FirstName", "*") %>
感谢您的答复! “Customer.FirstName”不起作用,因为客户是我的模型的一部分,但不是模型。我假设你的意思是Model.Customer.FirstName,我试过了(请参阅我的帖子编辑),但问题没有改变。 – 2009-04-14 16:52:03
客户是您的模型的财产,因此使用“Customer.FirstName”是适当的。它将使用反射来查找模型上的“客户”属性,然后在其上查找“FirstName”属性。如果找到匹配属性,您也不需要提供将从模型中检索的值 – tvanfosson 2009-04-14 16:55:27
我刚刚将帖子中的确切行粘贴到我的视图中。问题没有改变。另外,我尝试在GET操作方法中设置FirstName以“测试”。在浏览器中查看视图时,输入字段为空,因此,您建议的语法必须有错误 – 2009-04-14 17:14:14