返回列表&LT; T&GT;从观点到MVC 3控制器 [英] Return List<T> from view to controller in MVC 3
问题描述
目前,我有一个对象标签
定义如下:
I currently have an object Tag
defined as follows:
public class Tag
{
public string Name { get; set; }
}
现在,这是一个型号这我定义为一个集合属性:
Now, this is a collection property of a Model which I'm defining as:
public class MyModel
{
public string Name { get; set; }
public IList<Tag> Tags { get; set; }
}
在我看来,我有以下code:
In my view I have the following code:
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</div>
<div>
<!--
Here I'd like a collection of checkbox inputs, where the selected names
get passed back to my controller via the IList<Tag> collection
-->
</div>
<input type="submit" value="Submit" />
}
我如何通过我的模型的IList集合在我的复选框组(在评论中指定)返回选定的项目?
How do I return the selected items on my checkbox group (specified in comments) via the IList collection of my model?
推荐答案
使用编辑模板
对于有复选框,添加其他媒体资源相关联到你的标签
班组长指定它是否被选中与否。
For having the Checkbox, Add another Proeprty to your Tag
classs to specify whether it is selected or not.
public class Tag
{
public string Name { get; set; }
public bool IsSelected { set; get; }
}
现在从你的 GET
动作,你可以在模型中的标签
属性设置标签的列表,把它到视图。
Now from your GET
Action, you can set a List of Tags in your Model's Tags
Property and sent it to the View.
public ActionResult AddTag()
{
var vm = new MyModel();
//The below code is hardcoded for demo. you mat replace with DB data.
vm.Tags.Add(new Tag { Name = "Test1" });
vm.Tags.Add(new Tag { Name = "Test2" });
return View(vm);
}
现在让我们创建一个编辑模板,转到查看/ YourControllerName
并创建一个文件夹,名为 EditorTemaplates
和创建具有相同名称的新景观那里的房产类型的( Tag.cshtml
)。
Now Let's create an Editor Template, Go to The View/YourControllerName
and Create a Folder called EditorTemaplates
and Create a new View there with the same name as of the Property type ( Tag.cshtml
).
该内容添加到新的编辑模板了。
Add this content to the new editor template now.
@model Tag
<p>
<b>@Model.Name</b> :
@Html.CheckBoxFor(x => x.IsSelected) <br />
@Html.HiddenFor(x=>x.Name)
</p>
现在在你的主视图中,使用 EditorFor
HTML辅助方法调用你的编辑器的模板。
Now in your Main View, Call your Editor template using the EditorFor
Html Helper method.
@model MyModel
<h2>AddTag</h2>
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</div>
<div>
@Html.EditorFor(m=>m.Tags)
</div>
<input type="submit" value="Submit" />
}
现在,当您发布的形式,你的模型将在所选择复选框将其对 IsSelected
属性为true值的标签集合。
Now when You Post the Form, Your Model will have the Tags Collection where the Selected Checkboxes will be having a True value for the IsSelected
Property.
[HttpPost]
public ActionResult AddTag(MyModel model)
{
if(ModelState.IsValid)
{
//Check for model.Tags collection and Each items IsSelected property value.
//Save and Redirect(PRG pattern)
}
return View(model);
}
筛选
这篇关于返回列表&LT; T&GT;从观点到MVC 3控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!