Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC Dynamic Model Binding Prefix

Is there any way of changing the binding prefix with a value which comes from the request parameters?

I have many nested search popups, and all of them shares the same ViewModel.

I can add a binding prefix to all the fields when requesting for the Search filters, but i don't know how can i make the [Bind(Prefix = "")] to work with values coming from the request parameters.

// get the search filters with the bindingPrefix we need
public ActionResult Search(string bindingPrefix)
{
    ViewData.TemplateInfo.HtmlFieldPrefix = bindingPrefix;
    SearchViewModel model = new SearchViewModel
    {
        BindingPrefix = bindingPrefix
    };

    return PartialView("_SearchFilters", model); 
}

// post the search filters values
[HttpPost]
public ActionResult Search([Bind(Prefix = model.BindingPrefix)]SearchViewModel model)
{

}
like image 528
Catalin Avatar asked Jul 25 '13 13:07

Catalin


1 Answers

I don't know why you would want to do this, but this should work.

In your form on the view, have a hidden value

@Html.Hidden("BindingPrefix", Model.BindingPrefix)

Modify your action to the following

[HttpPost]
public ActionResult Search(SearchViewModel model)
{
    UpdateModel(model, model.BindingPrefix);
}
like image 159
Charlie Brown Avatar answered Nov 17 '22 15:11

Charlie Brown