我有一个ASP.NET MVC3应用程序,当用户点击我的锚标记时,我想将3个数据发送到一个动作:
<a onclick='editDescription(<#= DocID,FileName,Description #>)'></a>
这是调用我的操作的JavaScript:
function editDescription(docId,fileName,description) {
var url = "@Url.Content("~/OrderDetail/_EditDescription/")" + docId+'/'+
fileName + '/' + description;
//do the rest}
我的行动:
public ActionResult _EditDescription(string id,string filename, string descritpion)
我关注的部分是FileName和Description,因为这些可能是loooooong,我不希望网址如此显示:
http://localhost/OrderDetail/_EditDescription/123/some long filename.pdf/this is a long description for the name
如何将数据发送到我的操作而不必像查询字符串一样发送?感谢
答案 0 :(得分:16)
您可以使用jQuery $ .ajax方法:
<div id="what-I-want-updated">
<input id="whatever-the-id-is" type="text" value="@Model.ID" />
<br />
<input id="whatever-the-filename" type="text" value="@Model.Filename" />
<br />
<input id="whatever-the-description" type="text" value="@Model.Description" />
<br />
<button id="whatIsClicked">Update!</button>
</div> <!-- /#what-I-want-updated -->
<script>
// You're probably clicking something to initiate update
var $whatIsClicked = $('#whatIsClicked');
// .live persists on the page even after other ajax calls
// So when the thing is clicked
$whatIsClicked.live('click', function() {
// Grab the information needed to update
var theId = $('#whatever-the-id-is').val(); //Or it could be .text()
var theFilename = $('#whatever-the-filename').val();
var theDescript = $('#whatever-the-description').val();
// Let's edit the description!
$.ajax({
type: "POST",
url: "OrderDetail/_EditDescription", // the method we are calling
contentType: "application/json; charset=utf-8",
data: {id: theId, filename: theFilename, description: theDescript},
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
alert('Oh no :(');
}
});
});
</script>
即使它仍然有效,请确保将Controller方法更改为:
[HttpPost]
public ActionResult _EditDescription(string id, string filename, string descritpion)
答案 1 :(得分:2)
如果您希望通过ajax $.post
或使用[HttpPost]
属性执行操作,则可以填写表单的完整帖子。
答案 2 :(得分:0)
将您的操作声明为 POST
[HttpPost]
public ActionResult _EditDescription(string docId, string filename, string description)
创建一个不可见的HTML表单:
<form action="@Url.Content("~/OrderDetail/_EditDescription/")" method="post" name="editDescriptionForm">
<input type="hidden" name="docId" />
<input type="hidden" name="fileName" />
<input type="hidden" name="description" />
</form>
填写表格并用JS提交:
function editDescription(docId, fileName, description) {
document.editDescriptionForm.docId = docId;
...
document.editDescriptionForm.submit();
}