【发布时间】:2013-05-30 13:37:41
【问题描述】:
--对 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 方法...但是接收到的所有参数都是空的。
【问题讨论】:
-
顺便说一句,你可以在源代码中写
+,而不是调用HtmlDecode。 -
试过了,但我的程序会吐出我尝试的每一种格式。 +("+") -- ("++") -- "++" ..等等...
-
否;我的意思是文字字符
+。 C# 中不需要 HTML 转义;你可以写"+"。 -
哦,明白了。我使用的字符略有不同,而且更粗体。 =P
-
+ 是你使用的角色。您可以直接在源代码中编写它。
标签: c# asp.net-mvc asp.net-mvc-4 actionlink actionresult