Timestretch Timestretch - 4 months ago 14
Javascript Question

Submitting dynamically generated form through JavaScript in MVC

I am using specially styled input elements which cannot actually use input tags, so instead I am building and submitting a form via Javascript like this answer describes.
In short:


var form = document.createElement("form");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "id["+index+"]");
hiddenField.setAttribute("value", this.id);
form.submit();


Now as far as I know, in my MVC controller I have to retrieve the data like so:

public ActionResult Submit(string a = null, string b = null...)
{
//something
}


My issue with this is that the data I am submitting with this form is very simple and is ONLY a list of variable length of unknown numbers that serve as IDs to fields. For example:

[1,2,5,3,10,199999]

and I have no idea of the range or amount of these IDs.
How can I send this data back to my MVC page controller?

Answer

Do the following:

If you don't know the amount of strings passed, or they can vary, use params[] instead:

    [HttpPost]
    [ValidateJsonAntiForgeryToken]
    //See this: http://stackoverflow.com/a/24394578/1057052
    public ActionResult Submit(params string[] a)
    {
          //Read it like this!
          foreach (var myvar in a)
          {
             //Do whatever you want with it!
          }          
    }

Create a new file called ValidateJsonAntiForgeryTokenAttribute:

   [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple= false, Inherited = false)]
    public sealed class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            var httpContext = filterContext.HttpContext;
            var token = httpContext.Request.Headers["__RequestVerificationToken"] ?? httpContext.Request.Form["__RequestVerificationToken"];
            var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
            AntiForgery.Validate(cookie != null ? cookie.Value : null,token);
        }
    }

And put this in your .cshtml or .js file:

<script>
function AjaxSubmit(Url,Method, data, success)
{
    $.ajax( {
        url: Url,
        method: Method,
        data: data,
        contentType: false, 
        processData: false,
        //Protect 
        headers: {"__RequestVerificationToken" : document.getElementsByName('__RequestVerificationToken')[1].value},
        success: success
        });
    }
}


//use it like this:

var formData = new FormData();
    /**
    * Note: The "a" is the "key" or the name of the parameter
    * of your MVC controller.
    * The second parameter of the formData.append is the actual data
    * that you want to pass.
    *
    **/
    formData.append('a', "The Value I want to append. You can query for this value");
    formData.append('a', "The Value I want to append. You can query for this value");
    formData.append('a', document.getElementById('js-element').value);

    //You can modify alert("Success") for whatever the function you want.
    //Just remember to wrap it  inside function(){}
    AjaxSubmit("/MyController/Submit", "POST", formData, function(){alert("Success")});

</script>