Posted on Tuesday, July 25, 2017
Sometimes in your webpage, you will have a lot of form-controls so you might place it without using <form> element. And at the same time you need to get/post data to the server without ajax request because your ultimate goal would be a redirect to another page after sending data i.e. you don’t need a partial page refresh or xml/json data in return.
So, in this case, what we can do is to create a <form> element dynamically via javascript, add required attribute and child input elements to it, and append the form element to the html page (document object) and then finally submit the form.
Suppose, we have an action method as below:
public ActionResult ActionName(int[] x, string y)
{
//codes…
}
Javascript code in view:
1. Suppose we have dynamically select the values from the html page and put in two variables where one is an integer array and other is a string.
var variable1=[1,2,3,4];
var variable2= “James”;
2. Now create form and add required attributes
var formElement = document.createElement("form");
formElement.method = "post";
formElement.action = "/ControllerName/ActionName";
formElement.hidden = "hidden";
3. Then create and attach input elements to the form
for (var i = 0; i < variable1.length; i++)
{
var field = document.createElement("input");
field.name = "x[" + i + "]"; //field name must be ‘x’ i.e. same as first parameter in action
field.value = variable1[i];
formElement.appendChild(field);
}
var field = document.createElement("input");
field.name = "y"; //field name must be ‘y’ i.e. same as second parameter in action
field.value = variable2;
formElement.appendChild(field);
4. Finally add form element to body property of document object and trigger submit() method to submit the form
document.body.appendChild(formElement);
formElement.submit();