-- 对 C# 和 MVC 非常陌生--
在我的 Views/Tasks/Index.aspx 中,我在表格中包含以下行/单元格
<tr>
<td><%:
Html.ActionLink(
HttpUtility.HtmlDecode("+"),
"Insert",
"Tasks",
new { onclick = "InsertTask();" },
new { @class = "ActionButton AddButton" }
)
%></td>
<td><input type="text" id="txtAddName" style="width: 200px;" /></td>
<td><input type="text" id="txtAddDescription" style="width: 400px;"/></td>
<td><input type="text" id="txtAddStarting" style="width: 200px;" /></td>
<td><input type="text" id="txtAddEnding" style="width: 200px;" /></td>
</tr>
而且在同一个文件中,我有
<% if (ViewBag.Message != null) { %>
<%: ViewBag.Message %>
<% } %>
<script type="text/javascript">
function InsertTask() {
var name = $('#txtAddName').val();
var desc = $('#txtAddDescription').val();
var starting = $('#txtAddStarting').val();
var ending = $('#txtAddEnding').val();
$.ajax({
url: "Insert/" + name + "," + desc + "," + starting + "," + ending,
context: document.body
}).done(function () {
alert("done!");
});
}
</script>
在我的 Controllers/TasksController.cs 中,我有以下 ActionResult(s)
public ActionResult Index()
{
//Create an array of tasks
//Place task objects into variable tasks
//Create the view model
TaskIndexViewModel tivm = new TaskIndexViewModel
{
NumberOfTasks = tasks.Count(),
Tasks = tasks
};
//Pass the view model to the view method
return View(tivm);
}
public ActionResult Insert(string Name, string Description, String Starting, String Ending)
{
//Insert records to DB
//Notify
ViewBag.Message = "Insert Successful";
//Return success
return RedirectToAction("Index");
}
当我单击 ActionLink 元素时,它
- 不调用 JS 函数
- 是否调用 Insert ActionResult (不知何故甚至没有传递参数?)
- 页面刷新(我最终想摆脱)没有显示任何 ViewBag.Message
我的最终目标......是让 ActionLink 通过 AJAX / JQuery 调用 ActionResult,并显示“成功”响应消息......而无需重新加载整个页面。
编辑
从 SLaks 响应中,我将 ActionLink 更改为以下代码......并添加了“return false;” 到我的 JS 函数结束。
<td><%:
Html.ActionLink(
HttpUtility.HtmlDecode("+"),
"Insert",
"Tasks",
null,
new { onclick = "InsertTask();" , @class = "ActionButton AddButton" }
)
%></td>
它现在调用 .CS 控制器 ActionResponse 方法……但接收到的所有参数均为空。