- 对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元素时,它
我的最终目标是让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方法...但是收到的所有参数都是null。
答案 0 :(得分:1)
您需要从内联处理程序return false
来阻止浏览器执行默认操作(导航到链接)
答案 1 :(得分:1)
如果您将ajax调用更改为此,则应该有效:
$.ajax({
url: "Tasks/Insert",
data: { name: name, description: desc, starting: starting, ending: ending },
context: document.body
}).done(function () {
alert("done!");
});