Asp.net mvc Forms Collection Submission

What is the best practice of submitting forms in asp.net mvc. I am making the code as shown below, but I have a feeling that there is a better way. offers?

[AcceptVerbs(HttpVerbs.Post)] public ActionResult AddNewLink(FormCollection collection_) { string url = collection_["url"].ToString(); string description = collection_["description"].ToString(); string tagsString = collection_["tags"].ToString(); string[] tags = tagsString.Replace(" ","").Split(','); linkRepository.AddLink(url, description, tags); 
+7
asp.net-mvc
source share
2 answers

You can use the parameters directly; parameters will automatically be parsed and displayed on the correct type. The names of the parameters in the method must match the names of the parameters that are submitted from your form.

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult AddNewLink(string url, string description, string tagsString) { string[] tags = tagsString.Replace(" ","").Split(','); linkRepository.AddLink(url, description, tags); } 

As a rule, this works with more complex objects, if its properties can be set, and while your form keys are in the format objectName.PropertyName. If you need something more advanced, you should learn about model bindings .

 public class MyObject { public int Id {get; set;} public string Text {get; set;} } [AcceptVerbs(HttpVerbs.Post)] public ActionResult AddNewLink(MyObject obj) { string[] tags = obj.Text.Replace(" ","").Split(','); linkRepository.AddLink(url, description, tags); } 
+10
source share

In my opinion, the Binder model is cleaner. You can find out more at OdeToCode.com

In principle, you transfer your input from FormCollection to the desired model, as well as for validation.

 public class LinkModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var link = new Link(); link.Url = GetValue<string>(bindingContext, "url"); // ... and so on for all properties if (String.IsNullOrEmpty(url.Name)) { bindingContext.ModelState.AddModelError("Url", "..."); } return link; } private T GetValue<T>(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) 
+3
source share

All Articles