我需要使用javascript方法调用一个动作。那就是我有一个页面,其链接如下所示,
<a href="javascript:Sort();" >Click Me to Go</a>
我需要点击这个,我想调用一个动作,它将返回一个视图,我想要一个回复发生。
以下是我发现的工作方式,但我不确定这是否是正确的方法,有没有办法可以使用$ post,$ ajax或$ json做到这一点?
这是因为我也需要将值传递给动作。
function Sort() {
location.href='@Url.Action("ActioName")';
}
答案 0 :(得分:2)
我假设你没有在Url.Action(...)中提供路由值,你想要发布到操作的数据是由用户在客户端设置的吗?
如果是这样,一个非常简单的方法是使用带有隐藏字段的表单(或者如果您想直接进行用户交互,则可能是可见的),然后在Sort上设置这些字段,然后提交表单。
例如:
<form id='sortform' action='@Url.Action("ActionName")' method='POST'>
<input type='hidden' name='MyFirstSortValue'>
<input type='hidden' name='MySecondSortValue'>
</form>
和
function Sort() {
var formElem = document.getElementById('sortform');
formElem.MyFirstSortValue.value = "blah";
formElem.MySecondSortValue.value = "blah";
formElem.submit();
}
如果您只是让用户选择排序信息,那么我建议让表单输入可见并直接使用它们,而不是在调用Sort时间接设置它们。
完成上述操作后,您可以使用FormCollection通过控制器访问信息。例如:
[HttpPost]
public ActionResult ActionName(FormCollection form)
{
string myFirstSortValue = form["MyFirstSortValue"];
string mySecondSortValue = form["MySecondSortValue"];
// Do something to sort the data in the model...
return View(yourModel);
}
这将导致回传与正在传输的数据以及要显示的所需视图一起发生。
答案 1 :(得分:0)
function Sort() {
$.ajax({
url:"@Url.Action("ActioName")",
success:function(data){
//do some thing
}
})
}
答案 2 :(得分:0)
@Html.ActionLink("LinkText","Action","Controller")
试试这个
答案 3 :(得分:0)
如果你想通过javascript调用一个动作,那么下面就可以了。
var somedata = null;
$.ajax(
{
type: "POST",
url: '@Url.Action("ActioName")',
data: somedata,
cache: false,
success: function (result) {
//// if you want to go to a different page, then you can use
//// location.href='@Url.Action("ActioName")';
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});