MVC3如何张贴在控制器类中的一个列表? [英] MVC3 how to post a list within a class in controller?
问题描述
我有一个类:
公共类卡洛斯
{
公众诠释数量{获取;设置;}
公开名单<汽车>汽车{获取;设置;}
}公共类车{
公共字符串名称{;设置;}
}
我然后创建三辆车在列表中的汽车名单。然后,我显示使用内循环Model.Cars在屏幕上的信息。当我提交表单,数量字段,但汽车的有效值为null。
[HttpPost]
公众的ActionResult保存(卡洛斯名单)
{
//为什么list.Cars空当我张贴列表中的三个项目
}
查看:
模型=车,增加一排
增加新的编辑器模板与汽车<$c$c><tr><td>Name</td><td>Html.TextBoxFor(x=>Model.Name)</td></tr>$c$c>
和在主要观点:
模型=卡洛斯,增加了forloop
@ {的foreach(汽车在Model.Cars项)
{
@ Html.EditorFor(X =&GT;的项目);
}
使用的 EditorTemplate ,你会好的。
创建一个名为文件夹的 EditorTemplates ,并创建一个名为视图(编辑模板) Car.cshtml
现在添加下面的code这个新的看法。
@model车
&所述p为H.;
@ Html.TextBoxFor(X =&GT; x.Name)
&所述; / P&GT;
现在在你的主视图中,使用Html.EditorFor HTML辅助方法来调用这个编辑器模板
@model SO_MVC.Models.CarList
&LT; H2&GT;卡洛斯&LT; / H&GT;
@using(Html.BeginForm())
{
&所述p为H.; Quanitty&下; / P&GT;
@ Html.TextBoxFor(X =&GT; x.quantity)
@ Html.EditorFor(X =&GT; x.Cars)
&LT;输入类型=提交值=保存/&GT;
}
现在有一个HTTPPOst操作方法来接受的形式发布
[HttpPost]
公众的ActionResult卡洛斯(卡洛斯模型)
{
//现在检查model.Cars财产。
}
您现在看到的结果
I have a class:
public class CarList
{
public int quantity{get;set;}
public List<Car> Cars {get;set;}
}
public class Car {
public string Name {get;set;}
}
I then create a car list with three cars in the list. I then display info on the screen using for loop Model.Cars within a . When I submit the form, quantity field has a valid value but Cars is null.
[HttpPost]
public ActionResult Save(CarList list)
{
//why is list.Cars NULL when i am posting three items in the list
}
View: Model = Car, added a row
Added new editor template for Car with <tr><td>Name</td><td>Html.TextBoxFor(x=>Model.Name)</td></tr>
And in main view: Model = CarList, added the forloop
@{foreach (Car item in Model.Cars)
{
@Html.EditorFor(x=>item);
}
Use an EditorTemplate and you will be good.
Create a Folder Called "EditorTemplates" and create a view (the editor template) with the name Car.cshtml
Now Add the below code to this new view.
@model Car
<p>
@Html.TextBoxFor(x => x.Name)
</p>
Now in your Main View, Use the Html.EditorFor HTML helper method to call this editor template
@model SO_MVC.Models.CarList
<h2>CarList</h2>
@using (Html.BeginForm())
{
<p>Quanitty </p>
@Html.TextBoxFor(x => x.quantity)
@Html.EditorFor(x=>x.Cars)
<input type="submit" value="Save" />
}
Now have an HTTPPOst action method to accept the form posting
[HttpPost]
public ActionResult CarList(CarList model)
{
//Check model.Cars property now.
}
You will see the results now
这篇关于MVC3如何张贴在控制器类中的一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!