[英]Submitting dynamically generated form through JavaScript in MVC
我正在使用無法實際使用輸入標簽的特殊樣式的輸入元素,因此,我正在通過Javascript構建和提交表單, 如此答案所述。 簡而言之:
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中是否可以使用任何后備來獲得相同的結果?
請執行下列操作:
如果您不知道傳遞的字符串數量,或者它們可能有所不同,請改用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.