在ASP.NET MVC形式张贴到另一个模型 [英] Posting to another model from a form in ASP.NET MVC
问题描述
如果我有了一个模型的视图,可以说汽车。
If I have a view that has a model, lets say Car..
@model Project.Car
这视图内我要创建将数据发送到一个新的模式形式
inside that view I want to create a form that sends data to a new model
@using (Html.BeginForm("Add", "Controller"))
{
@Html.Hidden("ID", "1")
@Html.Hidden("UserID", "44")
@Html.TextArea("Description")
}
我发现,如果我的行为与我的定义视图模型它不工作(型号总是空):
I've noticed that if my action is defined with my ViewModel it does not work (model is always null):
[HttpPost]
public PartialViewResult Add(ViewModels.NewModel model)
不过,如果我使用它的工作原理的FormCollection:
However, if I use a FormCollection it works:
[HttpPost]
public PartialViewResult Add(FormCollection formCollection)
下面是视图模型:
public class NewModel
{
public int ID { get; set; }
public int UserID { get; set; }
public string Description { get; set; }
}
我的问题是,我可以从我的表单POST数据newModel,并向来?它坐落在观是正确的绑Project.Car。它是一种小型化,需要上传一组不同的数据有无关Project.Car在页面上。
My question is can I post data to NewModel from my form? The View that it sits on is correct to be tied to Project.Car. Its a small form on the page that needs to post a different set of data that has nothing to do with Project.Car.
推荐答案
您有您的模型和动作名称之间有差异。在这个例子中,你表现出的模式被称为添加
而在你的行动,你正在使用 ViewModels.NewModel
。更糟的是,你的看法是强类型到一个名为车
模式。凌乱的这一切。
You have a discrepancy between the name of your model and your action. In the example you have shown the model is called Add
whereas in your action you are using ViewModels.NewModel
. Even worse, your view is strongly typed to a model called Car
. Messy all this.
因此,通过定义一个正确的视图模型启动:
So start by defining a correct view model:
public class CarViewModel
{
public int ID { get; set; }
public int UserID { get; set; }
public string Description { get; set; }
}
然后控制器:
public class CarsController: Controller
{
public ActionResult Add()
{
var model = new CarViewModel
{
// don't ask me, those are the values you hardcoded in your view
ID = 1,
UserID = 44,
};
return View(model);
}
[HttpPost]
public PartialViewResult Add(CarViewModel model)
{
...
}
}
和相应的强类型以便您的视图模型:
and a corresponding strongly typed view to your view model:
@model CarViewModel
@using (Html.BeginForm())
{
@Html.HiddenFor(x => x.ID)
@Html.HiddenFor(x => x.UserID)
@Html.TextAreaFor(x => x.Description)
<button type="submit">Add</button>
}
这篇关于在ASP.NET MVC形式张贴到另一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!