同父视图使用一个局部视图下多次 [英] Using one Partial View Multiple times on the same Parent View
问题描述
我使用MVC3剃刀。我有一个场景,我必须用一个局部视图上多次同父视图。我遇到的问题是,当父视图获取呈现,它产生的局部视图中的输入控件相同的名称和ID。由于我的部分观点被绑定到不同的模型,视图时回发保存崩溃。任何想法如何使控件的ID /名称独特,$ P $可能是一些如何PFIX他们?
I am using MVC3 razor. I have a scenario where I have to use a partial view multiple times on the same parent view. The problem I am having is that when the Parent View gets rendered, it generates same names and ids of the input controls within those partial views. Since my partial views are binded to different models, when the view is posted back on "Save" it crashes. Any idea how can i make the control id/names unique, probably some how prefix them ?
等待
纳比勒
推荐答案
我个人preFER编辑模板,因为他们照顾这。例如,你可以有以下视图模型:
Personally I prefer using editor templates, as they take care of this. For example you could have the following view model:
public class MyViewModel
{
public ChildViewModel Child1 { get; set; }
public ChildViewModel Child2 { get; set; }
}
public class ChildViewModel
{
public string Foo { get; set; }
}
和以下的控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Child1 = new ChildViewModel(),
Child2 = new ChildViewModel(),
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
和 Index.cshtml
视图中:
@model MyViewModel
@using (Html.BeginForm())
{
<h3>Child1</h3>
@Html.EditorFor(x => x.Child1)
<h3>Child2</h3>
@Html.EditorFor(x => x.Child2)
<input type="submit" value="OK" />
}
和最后一部分是编辑模板(〜/查看/主页/ EditorTemplates / ChildViewModel.cshtml
)
and the last part is the editor template (~/Views/Home/EditorTemplates/ChildViewModel.cshtml
):
@model ChildViewModel
@Html.LabelFor(x => x.Foo)
@Html.EditorFor(x => x.Foo)
使用 EditorFor
您可以包括你的主视图模型和正确的名称的不同属性模板/ IDS将会产生。除了这个,你会得到你的视图模型中的POST操作正确填充。
Using the EditorFor
you can include the template for different properties of your main view model and correct names/ids will be generated. In addition to this you will get your view model properly populated in the POST action.
这篇关于同父视图使用一个局部视图下多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!