有什么方法可以使用来自请求参数的值更改绑定(bind)前缀?
我有许多嵌套的搜索弹出窗口,它们都共享相同的 ViewModel。
在请求搜索过滤器时,我可以为所有字段添加绑定(bind)前缀,但我不知道如何使 [Bind(Prefix = "")] 使用来自请求参数的值。
// 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)
{
}
最佳答案
我不知道您为什么要这样做,但这应该可行。
在 View 上的表单中,有一个隐藏的值
@Html.Hidden("BindingPrefix", Model.BindingPrefix)
将您的操作修改为以下内容
[HttpPost]
public ActionResult Search(SearchViewModel model)
{
UpdateModel(model, model.BindingPrefix);
}
关于Asp.Net MVC 动态模型绑定(bind)前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17859419/