How to handle MVC model binding prefix with same form repeated for each row of a collection?

廉价感情. 提交于 2019-12-04 12:37:27

I have a same problem with you, and there is my solution, hope it can help you.

add a hidden input in your EditorTemplate or Partial View

<input type="hidden" name="__prefix" value="@ViewData.TemplateInfo.HtmlFieldPrefix" />

define a custom model binder and override the BindModel method

public class CustomModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var prefixValue = bindingContext.ValueProvider.GetValue("__prefix");
        if (prefixValue != null)
        {
            var prefix = (String)prefixValue.ConvertTo(typeof(String));
            if (!String.IsNullOrEmpty(prefix) && !bindingContext.ModelName.StartsWith(prefix))
            {
                if (String.IsNullOrEmpty(bindingContext.ModelName))
                {
                    bindingContext.ModelName = prefix;
                }
                else
                {
                    bindingContext.ModelName = prefix + "." + bindingContext.ModelName;

                    // fall back
                    if (bindingContext.FallbackToEmptyPrefix && 
                        !bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
                    {
                        bindingContext.ModelName = prefix;
                    }
                }
            }
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

The model binder will trim the prefix and make the default model binding work.

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