如果我有一个有模型的 View ,比如说 Car..
@model Project.Car
在该 View 中,我想创建一个将数据发送到新模型的表单
@using (Html.BeginForm("Add", "Controller"))
{
@Html.Hidden("ID", "1")
@Html.Hidden("UserID", "44")
@Html.TextArea("Description")
}
我注意到,如果我的操作是用我的 ViewModel 定义的,它就不起作用(模型始终为 null):
[HttpPost]
public PartialViewResult Add(ViewModels.NewModel model)
但是,如果我使用 FormCollection,它会起作用:
[HttpPost]
public PartialViewResult Add(FormCollection formCollection)
这是 View 模型:
public class NewModel
{
public int ID { get; set; }
public int UserID { get; set; }
public string Description { get; set; }
}
我的问题是我可以将数据从我的表单发布到 NewModel 吗?它所在的 View 与 Project.Car 绑定(bind)是正确的。它是页面上的一个小表格,需要发布一组与 Project.Car 无关的不同数据。
最佳答案
是的,您可以将 View 强类型化到一个模型并将其发布到另一个模型。
这样做你有两个选择:
手动为每个输入字段提供正确的名称,以便默认 Binder 能够理解它并创建模型 ( example )。
虽然这有效,但这也意味着您必须注意拼写错误,如果您拼错了属性名称,您将不会遇到任何编译时错误。
在绑定(bind)到新模型类型的 View 中手动创建 HTML 帮助程序。然后它将正确地为您生成 HTML。
为了构建帮助程序,您需要一个包装器对象,该对象将以
IViewDataContainer
接口(interface)的形式公开您的模型实例。您可以在任何地方定义该包装器,包括模型本身:public class NewModel { public int ID { get; set; } public int UserID { get; set; } public string Description { get; set; } public class WrapperForHtmlHelper : System.Web.Mvc.IViewDataContainer { public System.Web.Mvc.ViewDataDictionary ViewData { get; set; } public WrapperForHtmlHelper(NewModel value) { this.ViewData = new System.Web.Mvc.ViewDataDictionary<NewModel>(value); } } }
然后在 View 中创建一个绑定(bind)到
NewModel
实例的助手:var ModelToPost = new YourApp.Models.NewModel() { ID = 1, UserID = 43, Description = "" } var hlp = new HtmlHelper<YourApp.Models.NewModel> (this.ViewContext, new YourApp.Models.NewModel.WrapperForHtmlHelper(ModelToPost) );
然后像往常一样使用助手:
@hlp.HiddenFor(m => m.ID) @hlp.HiddenFor(m => m.UserID) @hlp.TextAreaFor(m => m.Description)
然后您的
PartialViewResult Add(ViewModels.NewModel model)
将正确接收数据。
关于c# - 从 ASP.NET MVC 中的表单发布到另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15094054/