Search code examples
asp.net-mvcparameters

Forms Collection when submitting


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.

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

Solution

  • You can use the parameters directly; the parameters will automatically get parsed and casted to its correct type. The parameter names in the method must match the parameter names that are posted 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);
    }  
    

    This generally works on more complex objects as well, as long as its properties can be set, and as long as your form keys are in the format objectName.PropertyName. If you need anything more advanced, you should look into model binders.

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