0

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?

EDIT: The currently selected answer does indeed answer the question as I asked it. I didn't get the chance to test this till now but there is no support for FormData in IE9. Is there any fallback I can use to get the same result in IE9?

Community
  • 1
  • 1
Brandon Slaght
  • 1,025
  • 1
  • 12
  • 34

1 Answers1

1

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>
Jose A
  • 10,053
  • 11
  • 75
  • 108
  • 1
    This worked for me, except to get the data to form an array, instead of `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");` you have to do `formData.append('[0]', "The Value I want to append. You can query for this value"); formData.append('[1]', "The Value I want to append. You can query for this value");...ect` – Brandon Slaght Jul 13 '16 at 15:15
  • 1
    @Timestretch: cool :D. Yeah, that happens. Next time you're trying to do a complex object (a class that you created by yourself) you put the name of the parameter defined in the action method and append the indexes. For example in this case, the parameter is called "a", so it would be "a[0]", "a[1]", etc. – Jose A Jul 13 '16 at 19:03