jQuery 如何使用javascript函数在MVC中调用URL动作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8992721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call URL action in MVC with javascript function?
提问by gardarvalur
I′m trying to render url action with javascript in an MVC project. I capture an event on my page which calls this function but I′m not sure how to call this certain URL.
我正在尝试在 MVC 项目中使用 javascript 呈现 url 动作。我在我的页面上捕获了一个调用这个函数的事件,但我不确定如何调用这个特定的 URL。
Can anyone help me please? :)
有人可以帮我吗?:)
function onDropDownChange(e) {
var url = '/Home/Index/' + e.value;
//What now...?
}
-----------Edited-----------------------
-----------已编辑--------------
Here′s my controller action:
这是我的控制器操作:
public ActionResult Index(int? id)
{
var tmpToday = DateTime.Now;
var today = new DateTime(tmpToday.Year, tmpToday.Month, tmpToday.Day, 0, 0, 0);
if (id != null)
{
var num = id.GetValueOrDefault();
var rentableUnits = new List<Unit>();
_unitLogic.GetAllRentableUnitsByArea(num, rentableUnits);
var allAvailabilities = new ShowAvailability[rentableUnits.Count];
for (int i = 0; i < rentableUnits.Count; i++)
{
var sTime = GetFirstDayOfMonth(today);
var eTime = GetLastDayOfMonth(today);
allAvailabilities[i] = new ShowAvailability(sTime, eTime.AddHours(23.0).AddMinutes(59.0), rentableUnits);
today = today.AddMonths(1);
}
var showAvailability = new List<ShowAvailability>(allAvailabilities);
return View(new HomeFormViewModel(showAvailability));
}
else
{
var allAvailabilities = new ShowAvailability[12];
for (int i = 0; i < 12; i++)
{
var sTime = GetFirstDayOfMonth(today);
var eTime = GetLastDayOfMonth(today);
allAvailabilities[i] = new ShowAvailability(sTime, eTime.AddHours(23.0).AddMinutes(59.0));
today = today.AddMonths(1);
}
var showAvailability = new List<ShowAvailability>(allAvailabilities);
return View(new HomeFormViewModel(showAvailability));
}
}
#
I′m using Telerik extension for my DropDownList which fires the javascript function, this is in fact a Razor View:
我正在为我的 DropDownList 使用 Telerik 扩展来触发 javascript 函数,这实际上是一个 Razor 视图:
@(Html.Telerik().DropDownList()
.Name("DropDownList")
.Items(area =>
{
area.Add().Text("?ll sv?ei").Value("0").Selected(true);
foreach (Unit a in Model.Areas)
{
area.Add().Text(a.Name).Value(a.UnitID.ToString());
}
})
.HtmlAttributes(new { style = "width: 130px;" })
.ClientEvents(clev => clev.OnChange("onDropDownChange"))
)
Here′s the script:
这是脚本:
function onDropDownChange(e) {
var url = '/Home/Index/' + e.value;
$.ajax({
type: "GET",
url: url,
data: {},
dataType: "html"
});
}
回答by Jorge
I'm going to give you 2 way's to call an action from the client side
我将给你 2 种从客户端调用操作的方法
first
第一的
If you just want to navigate to an action you should call just use the follow
如果您只想导航到您应该调用的操作,请使用以下命令
window.location = "/Home/Index/" + youid
Notes:that you action need to handle a get type called
注意:您的操作需要处理名为的 get 类型
Second
第二
If you need to render a View you could make the called by ajax
如果你需要渲染一个视图,你可以通过 ajax 调用
//this if you want get the html by get
public ActionResult Foo()
{
return View(); //this return the render html
}
And the client called like this "Assuming that you're using jquery"
客户端这样调用“假设您正在使用 jquery”
$.get('your controller path', parameters to the controler , function callback)
or
或者
$.ajax({
type: "GET",
url: "your controller path",
data: parameters to the controler
dataType: "html",
success: your function
});
or
或者
$('your selector').load('your controller path')
Update
更新
In your ajax called make this change to pass the data to the action
在您的 ajax 调用中进行此更改以将数据传递给操作
function onDropDownChange(e) {
var url = '/Home/Index'
$.ajax({
type: "GET",
url: url,
data: { id = e.value}, <--sending the values to the server
dataType: "html",
success : function (data) {
//put your code here
}
});
}
UPDATE 2
更新 2
You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div
in your view and do something like this
你不能在你的回调“windows.location”中这样做,如果你想要它去渲染一个视图,你需要div
在你的视图中放置一个并做这样的事情
in the view where you are that have the combo in some place
在你所在的地方有组合的视图
<div id="theNewView"> </div> <---you're going to load the other view here
in the javascript client
在 javascript 客户端中
$.ajax({
type: "GET",
url: url,
data: { id = e.value}, <--sending the values to the server
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
With this i think that you solve your problem
有了这个,我认为你解决了你的问题
回答by David Hoerster
Within your onDropDownChange
handler, just make a jQuery AJAX call, passing in any data you need to pass up to your URL. You can handle successful and failure calls with the success
and error
options. In the success
option, use the data contained in the data
argument to do whatever rendering you need to do. Remember these are asynchronous by default!
在您的onDropDownChange
处理程序中,只需进行 jQuery AJAX 调用,传入您需要传递到您的 URL 的任何数据。您可以使用success
和error
选项处理成功和失败的调用。在success
选项中,使用data
参数中包含的数据执行您需要执行的任何渲染。请记住,这些默认情况下是异步的!
function onDropDownChange(e) {
var url = '/Home/Index/' + e.value;
$.ajax({
url: url,
data: {}, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function(data) { alert('got here with data'); },
error: function() { alert('something bad happened'); }
});
}
jQuery's AJAX documentation is here.
jQuery 的 AJAX 文档在这里。
回答by scrappedcola
try:
尝试:
var url = '/Home/Index/' + e.value;
window.location = window.location.host + url;
That should get you where you want.
那应该可以让你到达你想要的地方。
回答by davaus
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
无论服务器设置如何,确保您获得正确 url 的另一种方法是将 url 放入页面上的隐藏字段中并引用它的路径:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
然后你就可以在你的 ajax 调用中得到值:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
我多年来一直在使用它来应对服务器的奇怪问题,因为它总是构建正确的 url。如果您将所有隐藏字段放在 html 的一个部分中,或者制作一个单独的剃刀部分来保存它们,它也可以使跟踪控制器方法调用的变化变得轻而易举。