Asp.Net MVC Dynamic Model Binding Prefix

折月煮酒 提交于 2019-12-22 08:24:53

问题


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)
{

}

回答1:


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


来源:https://stackoverflow.com/questions/17859419/asp-net-mvc-dynamic-model-binding-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!