我正在渲染部分 View 作为 Ajax 请求的一部分。
当我从 View 中调用局部 View 时:
int i=0;
foreach(var rule in Model.Rules) {
@Html.Partial("ValidationRuleRow", rule, new ViewDataDictionary {
TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = string.Format("Rules[{0}]", i) } })
i++;
}
我可以设置 HtmlFieldPrefix 以允许正确的模型绑定(bind)。
我希望用户能够通过 ajax 即时添加新的 ValidationRuleRow,例如:
$.ajax({
type: "GET",
url: "/Monitors/NewMonitorValidationRule",
success: function (data, textStatus, jqXHR) {
var element = $(data);
$("#ValidationRuleContainer").append(element);
}
});
所以我在我的 Controller 中有一个 Action 来获取 HTML:
public ActionResult NewMonitorValidationRule()
{
ValidationRule rule = new ValidationRule{Id = TempSurrogateKey.Next};
var view = PartialView("ValidationRuleRow", rule);
// CODE TO SET PartialView field prefix
return view;
}
返回的 HTML 没有前缀。从 Controller 中的 Action 调用 PartialView 时,无论如何要设置前缀吗?
最佳答案
更好的是,您可以在 Controller 操作中设置 ViewData.TemplateInfo.HtmlFieldPrefix,
public Actionresult MyAction()
{
...
ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
return PartialView("MyView", viewmodel);
}
View 模型中不需要 ViewBag 或属性。
关于asp.net-mvc-3 - ASP.NET MVC3 在调用 Controller.PartialView 时添加 HtmlFieldPrefix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6617768/