C# 对内部模型属性使用HtmlHelper
我的一个Asp.net MVC视图有这样的模型结构:C# 对内部模型属性使用HtmlHelper,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我的一个Asp.net MVC视图有这样的模型结构: public class MyModel{ public AnotherModel1 Prop1 {get;set;} public AnotherModel2 Prop2 {get;set;} } public class AnotherModel1{ public InnerModel InnerProp1 {get;set;} public InnerModel InnerProp2 {get;set;}
public class MyModel{
public AnotherModel1 Prop1 {get;set;}
public AnotherModel2 Prop2 {get;set;}
}
public class AnotherModel1{
public InnerModel InnerProp1 {get;set;}
public InnerModel InnerProp2 {get;set;}
public InnerModel InnerProp3 {get;set;}
}
public class AnotherModel2{
public InnerModel InnerProp1 {get;set;}
public InnerModel InnerProp2 {get;set;}
}
public class InnerModel {
public string Input {get;set;}
}
这意味着,MyModel是传递给视图的通用模型。其他一些模型AnotherModel1、AnotherModel2包含InnerModel作为属性
我想创建一个助手函数,它将知道如何渲染InnerModel。
然后,在我的页面视图中,我希望能够编写类似
@RenderInnerModel(m=>m.Prop1.InnerProp1)
问题是,我不知道如何将htmlhelper传递到我的函数中,以便能够在助手中使用@Html.TextBoxFor(m=>m.Input)
虽然这个问题可以通过使用每个InnerModel的部分视图来解决,但我希望有一个参数化的辅助函数,并且不想把复杂的部分模型搞得一团糟,例如使用元组等
编辑 虽然EditorFor似乎几乎就是我想要的,但我仍然想了解,是否有可能拥有类似的东西
var modelHelper = new HtmlHelper<InnerModel>(ViewContext, this);
var modelHelper=newhtmlhelper(ViewContext,this);
但是在MyModel的上下文中?谢谢 您的控制器:
public class AnotherModel
{
public InnerModel InnerProp1 { get; set; }
public InnerModel InnerProp2 { get; set; }
}
public class InnerModel
{
public string Input { get; set; }
}
public class EditorExampleController : Controller
{
//
// GET: /EditorExample/
public ActionResult Index()
{
AnotherModel model = new AnotherModel();
model.InnerProp1 = new InnerModel { Input = "test 1" };
model.InnerProp2 = new InnerModel { Input = "test 2" };
return View(model);
}
}
你的看法:
@model MVCApp.Controllers.AnotherModel
<h2>Editor template</h2>
@Html.EditorFor(_ => _.InnerProp1)
@Html.EditorFor(_ => _.InnerProp2)
@model MVCApp.Controllers.AnotherModel
编辑器模板
@Html.EditorFor(\u=>\ u0.InnerProp1)
@Html.EditorFor(\u=>\ u0.InnerProp2)
在“视图”中的“共享”文件夹上创建一个名为“EditorTemplates”的新文件夹,然后添加一个局部视图“InnerModel.cshtml”:
@model MVCApp.Controllers.InnerModel
@如果(Model.Input==“测试2”)
{
@模型输入
}
其他的
{
@模型输入
}
这是一个简单的实现,如果您需要,我可以发布一个自定义的HtmlHelper我想您需要自定义的editorGood答案,还请注意,EditorFor可以使用模板名称进行参数化,以防在EditorTemplates中有给定模型的多个视图。@lucas roselli是的,EditorFor是一个很好的捕获,但我希望它被参数化。我发现我可以在InnerModel中使用一些伪属性,并将其用作参数,但这并不漂亮。请你给个建议好吗?自定义HtmlHelper可能会有所帮助,谢谢@好吧,我完全理解,你能给我一个你想要的真实例子吗,然后我可以做一个更具体的例子response@lucas-roselli好的,比方说,我有InnerModel.Input,用Html.dropDownList表示控件,我想传递可能的选择项,每个模型的选择项不同。
@model MVCApp.Controllers.InnerModel
@if (Model.Input == "test 2")
{
<h4>@Model.Input</h4>
}
else
{
<h2>@Model.Input</h2>
}