我有一个特殊情况,我需要一个带有“添加新记录”行的网格,该行存在于MVC表单中。
由于我无法提交新的记录详细信息,而没有提交整个表单,我决定让记录提交按钮调用一个Javascript方法,该方法应该将数据发送到我的控制器上的方法。简而言之,这是我正在做的一个例子。下面的代码是从我的项目中复制粘贴的,只是为了简洁而进行了少量修改。
...
<table>
CODE HERE FOR MY GRID...
</table>
...
<input class="data_field" id="MainSession_Name" type="text" />
<input class="data_field" id="MainSession_Type" type="text" />
<button id="btnAddMainSession" class="button" onclick="SubmitMainSession()" type="button">Add Session</button>
...
<script>
var SubmitMainSession = function()
{
var data = {
Name: $('MainSession_Name').val(),
RecType: $('MainSession_Type').val(),
};
$.post(
{
url: "/Session/Add",
data: data,
callback: function(res, status)
{
if (res !== "OK")
alert("There was a problem processing the request. " + res);
else
location.reload(true);
}
});
}
</script>
我的意图很简单。在用户输入会话的新详细信息后,他们将单击Add Session
按钮。 JQuery将发出POST请求将我的数据传递给我的页面控制器。
以下是我的控制器的缩写变体:
//Index that initially loads the data.
public ActionResult Index(int id = -1)
{
SessionModel sm = new SessionModel(id);
sm.CanEdit = true;
return View(sm);
}
//The containing model manages a HUGE form,
//across multiple BootStrap.js tabs. We save
//all other, non-sub-record related deets here.
public ActionResult Submit(SessionModel model)
{
model.Save();
return Redirect(Url.Content("~/"));
}
//Since there are multiple grids, I need to
//have a way to add new Session records.
//This is my first attempt at trying to
//create a POST method on my controller.
[HttpPost]
public string Add(AddSessionObject data)
{
//If I can ever get here, I'll save the data.
return "OK";
}
public class AddSessionObject
{
public string Name;
public string RecType;
}
我遇到的是,当我在JQuery中进行$ .post(...)调用时,MVC总是调用Index(...)方法,而不是Add(...)方法。我做错了什么?
答案 0 :(得分:2)
尝试使用以下语法:
var data = {
Name: $('MainSession_Name').val(),
RecType: $('MainSession_Type').val(),
};
$.post("/Session/Add", data, function(res, status) {
if (res !== "OK")
alert("There was a problem processing the request. " + res);
else
location.reload(true);
});