22

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?

2 Answers 2

36
+250

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Gave you a bounty for that one, well played.
Thanks a lot, caught me by surprise there :)
Except sometimes input id attributes won't render... See my question
18

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

1 Comment

Good call. I ended up using ViewBag rather than add it to the view model but this workaround is sufficient. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.