问题描述
我渲染的局部视图作为Ajax请求的一部分。
I am rendering a partial view as part of an Ajax request.
当我打电话从视图局部视图:
When I call the partial view from a 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++;
}
我能够设置HtmlField preFIX允许适当的模型绑定。
I am able to set the HtmlFieldPrefix to allow for proper Model binding.
我希望用户能够通过AJAX添加一个新的ValidationRuleRow动态,如:
I want the user to be able to add a new ValidationRuleRow on the fly via ajax, like:
$.ajax({
type: "GET",
url: "/Monitors/NewMonitorValidationRule",
success: function (data, textStatus, jqXHR) {
var element = $(data);
$("#ValidationRuleContainer").append(element);
}
});
所以,我有我的控制器的操作来获取HTML:
So I have an action in my controller to get the 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没有一个preFIX。反正有没有设定一个控制器调用从一个动作PartialView时preFIX?
The returned HTML doesn't have a prefix. Is there anyway to set a prefix when calling a PartialView from an Action in a Controller?
推荐答案
您可以一起作为视图模型的一部分传递这样的信息:
You could pass this information along as part of the view model:
public ActionResult NewMonitorValidationRule()
{
ValidationRule rule = new ValidationRule{Id = TempSurrogateKey.Next};
// CODE TO SET PartialView field prefix
rule.MyPrefix = "Rule[153]";
return PartialView("ValidationRuleRow", rule);
}
和 ValidationRuleRow.cshtml
局部视图使用此视图模型属性来设置preFIX里面:
and inside the partial view ValidationRuleRow.cshtml
use this view model property to set the prefix:
@{
if (!string.IsNullOrEmpty(Model.MyPrefix))
{
ViewData.TemplateInfo.HtmlFieldPrefix = Model.MyPrefix;
}
}
这篇关于ASP.NET MVC3调用Controller.PartialView时添加HtmlField preFIX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!