我有一个特殊情况,我需要一个带有“添加新记录”行的网格,该行存在于 MVC 表单中。
由于我无法在不提交整个表单的情况下提交新记录详细信息,因此我决定让记录提交按钮调用 Javascript 方法,该方法应将数据 POST 到 Controller 上的方法。简而言之,这是我正在做的一个例子。下面的代码是从我的项目中复制粘贴的,为了简洁起见,只做了一些小的修改。
...
<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>
我的意图很简单。用户输入 session 的新详细信息后,他们将单击添加 session
按钮。 JQuery 将发出 POST 请求,将我的数据传递到我的页面 Controller 。
这是我的 Controller 的缩写版本:
//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(...) 方法。我做错了什么?
最佳答案
尝试使用以下语法:
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);
});
关于javascript - JQuery 未在我的 Controller 上调用 HttpPost 方法。我该如何解决这个问题,或者可能出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37621404/