在MVC中通过JavaScript提交动态生成的表单

时间:2016-07-12 14:35:24

标签: javascript html asp.net-mvc forms

我使用的是特殊样式的输入元素,它实际上不能使用输入标签,所以我正在构建并通过Javascript来提交表单,例如this回答描述。 简而言之:

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

据我所知,在我的MVC控制器中,我必须像这样检索数据:

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

我的问题是,我使用此表单提交的数据非常简单,只是一个可变长度的未知数字列表,用作字段的ID。例如:
[1,2,5,3,10,199999]
我不知道这些ID的范围或数量。   如何将此数据发送回我的MVC页面控制器?

编辑:当前选择的答案确实回答了我提出的问题。到目前为止我没有机会测试这个,但IE9中没有对FormData的支持。我可以使用任何后备来在IE9中获得相同的结果吗?

1 个答案:

答案 0 :(得分:1)

执行以下操作:

如果您不知道传递的字符串数量,或者它们可以变化,请使用params []代替:

    [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!
          }          
    }

创建一个名为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);
        }
    }

并将其放在.cshtml或.js文件中:

<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>