从视图中调用Controller中的Action并发送参数 [英] Call Action in Controller From View and send parameter

查看:79
本文介绍了从视图中调用Controller中的Action并发送参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过JavaScript操作在MVC中的控制器内调用方法. javascript操作应该在控制器内部调用此方法并向其发送一些参数.

I am trying to call a method inside a controller in MVC from a javascript action. The javascript action is supposed to invoke this method inside the controller and send some parameters to it.

我的Javascript代码如下:

My Javascript code looks like this:

location.href = '@Url.Content("~/Areas/MyArea/MyMethod/"+Model.MyId)';

我的方法定义如下:

[HttpGet] 
public ActionResult MyMethod(int? MyId) 
{ 
   doSomething(MyId); 
   return View("MyView"); 
}

但是,当我调试应用程序时,调用该方法时,MyId参数将作为null而不是作为模型中MyId参数的当前值传递.我该怎么做才能正确发送或检索该值?谢谢!

However, when i debug the application, when the method is called the MyId parameter is passed as null and not as the current value of the MyId parameter in my model. What can I do to correctly send or retrieve this value? Thanks!

推荐答案

在您的路由定义中,我假设参数名为{id}而不是{MyId}:

In your route definition I suppose that the parameter is called {id} and not {MyId}:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.MapRoute(
        "MyArea_default",
        "MyArea/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

因此,请尽量保持一致,并相应地调整控制器操作参数名称:

So try to be more consistent and adapt your controller action parameter name accordingly:

[HttpGet] 
public ActionResult MyMethod(int? id) 
{ 
    doSomething(id); 
    return View("MyView");
}

此外,您可能想使用url帮助器,而不是在JavaScript代码中对某些url模式进行硬编码:

Also you probably wanna use url helpers instead of hardcoding some url patterns in your javascript code:

window.location.href = '@Url.Action("MyMethod", "SomeControllerName", new { area = "MyArea", id = Model.MyId })';

Url.Content帮助器用于引用站点中的静态资源,例如javascript,css和图像文件.对于控制器动作,最好使用Url.Action辅助方法.

The Url.Content helper is used to reference static resources in your site such as javascript, css and image files. For controller actions it's much better to use the Url.Action helper method.

这篇关于从视图中调用Controller中的Action并发送参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆