这里是我的.cshtml代码:
@model WebComposite.Models.MyModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.id)
@Html.TextBoxFor(m => m.name)
}
@Scripts.Render("~/Scripts/MyScript.js")
这里是MyScript.js中的代码:
$('form').submit(function (e)
{
e.preventDefault();
//normal Ajax (my own custom version as i'm sure every one has one of these:)
SimpleAjax("MyAction", function () { alert("Done"); });
});
Controller代码:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
//Problem here is model.id and model.name are empty
}
任何想法? 提前谢谢
答案 0 :(得分:0)
快速浏览后,我猜解决方案非常简单(谢谢jquery !!): 只需序列化表单中的所有内容,然后通过ajax调用将其发送回控制器:
$("form").serializeArray();
这是我自己的Ajax调用的完整实现 有3个函数(你将调用SimplAjaxPost(url,funcDelegate),它将为你完成剩下的工作
function Ajax(url, dataObj, getOrPost, theContext, theContentType, theDataType, successFuncName, failedFuncName, alwaysFuncName)
{
//GET or POST:
if (getOrPost == null) { getOrPost = 'POST'; }
//Header (what we're sending to the server): http://stackoverflow.com/questions/2722750/ajax-datatype
if (theContentType == null) { theContentType = 'application/x-www-form-urlencoded; charset=UTF-8'; }
//response (what we're expeting in return):http://stackoverflow.com/questions/2722750/ajax-datatype
if (theDataType == null) { theDataType = ""; }
//exposing "this" to whatever: http://stackoverflow.com/questions/5097191/ajax-context-option
if (theContext == null) { theContext = document.body; }
var theURL = NoCache(url);
$.ajax(
{
url: theURL,
data: dataObj,
type: getOrPost,
contentType: theContentType,
dataType: theDataType,
context: theContext,
async: false,
success: successFuncName,
fail: failedFuncName,
always: alwaysFuncName,
complete: AjaxScripts
});
}
function SimpleAjax(url, successFunctionName)
{
var dataObj = null;
Ajax(url, dataObj, null, null, null, null, successFunctionName, null, null)
}
function SimpleAjaxPost(url, successFunctionName)
{
var dataObj = null;
if ($("form").length == 1)
{
dataObj = $("form").serializeArray();
}
Ajax(url, dataObj, null, null, null, null, successFunctionName, null, null)
}
function NoCache(url)
{
var t = new Date();
var qps = "?";
if (url.indexOf("?") > 0)
{
qps = "&";
}
return url + qps + t.getYear() + t.getMonth() + t.getDay() + t.getHours() + t.getMinutes() + t.getSeconds() + t.getMilliseconds();
}