[英]Returning an EditorTemplate as a PartialView in an Action Result
I have a model similar to this: 我有一个类似的模型:
public class myModel
{
public ClassA ObjectA {get; set;}
public ClassB ObjectB {get; set;}
}
In my main view, I have tags similar to this: 在我的主视图中,我有类似这样的标签:
<div id="section1">
<%=Html.EditorFor(m => m.ObjectA)%>
</div>
<div id="section2">
<%=Html.EditorFor(m => m.ObjectB)%>
</div>
ClassA and ClassB both have Editor templates defined. ClassA和ClassB都定义了编辑器模板。
I created some JavaScript that makes an Ajax call to reload the section1 div. 我创建了一些JavaScript,它使Ajax调用重新加载section1 div。 I want the action method to return the editor for ObjectA, ClassA.ascx that is in the EditorTemplates folder.
我希望action方法返回EditorTemplates文件夹中ObjectA,ClassA.ascx的编辑器。
I have the following in my Action method: 我的Action方法中有以下内容:
public ActionResult GetData(int input)
{
// Process input here and create modelData
return PartialView("ClassA", modelData);
}
This gives an error because it cannot find the ClassA view. 这会产生错误,因为它无法找到ClassA视图。
My solution has been to create a PartialView in the Views folder called "GetData" and my return renders the GetData view. 我的解决方案是在Views文件夹中创建一个名为“GetData”的PartialView,然后我的返回呈现GetData视图。 The GetData view has only one line of code:
GetData视图只有一行代码:
<%=Html.RenderForModel()%>
This does work, but I was wondering if there was a way for an action method to return and editor template? 这确实有效,但我想知道是否有一种方法可以返回动作方法和编辑模板?
Bonus points for gift wrapping: 礼品包装的奖励积分:
public class CustomControllerBase : Controller
{
public PartialViewResult EditorFor<TModel>(TModel model)
{
return PartialView("EditorTemplates/" + typeof(TModel).Name, model);
}
public PartialViewResult DisplayFor<TModel>(TModel model)
{
return PartialView("DisplayTemplates/" + typeof(TModel).Name, model);
}
}
Have the controller (called, say, MyController) inherit from CustomControllerBase, and then: 让控制器(称为MyController)继承自CustomControllerBase,然后:
public ActionResult MyAction(int id)
{
return EditorFor(new MyViewModel(id));
}
The code will be looking for "~/Views/MyController/EditorTemplates/MyViewModel.ascx". 代码将查找“〜/ Views / MyController / EditorTemplates / MyViewModel.ascx”。
return PartialView("~/EditorTemplates/ClassA.ascx", modelData);
this worked for me ( mvc 4 ) 这对我有用 ( mvc 4 )
public ActionResult GetData(int input)
{
// Process input here and create modelData
return PartialView("EditorTemplates/ClassA", modelData);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.