asp.net mvc Forms Collection when submitting

后端 未结 2 809
温柔的废话
温柔的废话 2020-12-29 14:27

what is the best practice for submitting forms in asp.net mvc. I have been doing code like this below but i have a feeling there is a better way. suggestions?



        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 15:21

    In my opinion, the Model Binder is cleaner. You can learn more at OdeToCode.com

    Basically, You wrap your input from a FormCollection to a desirable model as well as validation.

    public class LinkModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var link = new Link();
            link.Url = GetValue(bindingContext, "url");
            // ... and so on for all properties
    
            if (String.IsNullOrEmpty(url.Name))
            {
                bindingContext.ModelState.AddModelError("Url", "...");
            }
    
            return link;
        }
    
        private T GetValue(ModelBindingContext bindingContext, string key) 
        {
            ValueProviderResult valueResult;
            bindingContext.ValueProvider.TryGetValue(key, out valueResult);            
            return (T)valueResult.ConvertTo(typeof(T));
        }  
    }
    

    In the controller

    public ActionResult AddNewLink(Link link)
    

提交回复
热议问题