ASP.NET MVC3 add a HtmlFieldPrefix when calling Co

2019-01-11 01:44发布

问题:

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++;
}

I am able to set the HtmlFieldPrefix to allow for proper Model binding.

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);
    }
});

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;
}

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?

回答1:

Even better, you can set ViewData.TemplateInfo.HtmlFieldPrefix inside the controller action,

public Actionresult MyAction()
{
   ...
   ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";

   return PartialView("MyView", viewmodel);
}

There's no need for ViewBag or a property in your view model.



回答2:

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);
}

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;
    }
}