Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 add a HtmlFieldPrefix when calling Controller.PartialView

Tags:

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?

like image 914
Michael Nelson Avatar asked Jul 07 '11 22:07

Michael Nelson


2 Answers

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.

like image 137
Thorsten Westheider Avatar answered Sep 20 '22 14:09

Thorsten Westheider


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;     } } 
like image 23
Darin Dimitrov Avatar answered Sep 21 '22 14:09

Darin Dimitrov