Javascript 在MVC中使用javascript调用控制器方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12231583/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:27:32  来源:igfitidea点击:

Using javascript to call controller method in MVC

javascriptjqueryajaxasp.net-mvc

提问by Christian

Im trying to make a table row work as a link to another view in my mvc website. Instead of using the standard "Details" link provided by the auto generated table list, I would like to use the table row as a link to the "Details" view instead. So somehow I need to make the row work as a link. Each rom has a unique id that I need to pass on to the controller method. I have tried different solutions but noting happens when I press on the table row...

我试图将表格行作为到我的 mvc 网站中另一个视图的链接。我不想使用自动生成的表格列表提供的标准“详细信息”链接,而是使用表格行作为指向“详细信息”视图的链接。所以不知何故我需要使行作为链接工作。每个 rom 都有一个唯一的 ID,我需要将其传递给控制器​​方法。我尝试了不同的解决方案,但是当我按下表格行时会发生注意......

So far this is what I have:

到目前为止,这就是我所拥有的:

<script type="text/javascript">
$(document).ready(function(){
    $('#customers tr').click(function () {
        var id = $(this).attr('id');
        $.ajax({
            url: "Customer/Details" + id,
            succes: function () { }
        });
    })
})
</script>

My controller method:

我的控制器方法:

public ActionResult Details(int id)
{
    Customer model = new Customer();
    model = this.dbEntities.Customers.Where(c => c.Customer_ID == id).Single();
    return View(model);
}

Global.asax:

全球.asax:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }     
    );

    routes.MapRoute(
        "CustomerDetails",
        "Customer/Details/{id}",
        new { controller = "Customer", action = "Details", id = "" }
    );
}

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // Use LocalDB for Entity Framework by default
    Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

回答by Matt Cashatt

Here is what I would do:

这是我会做的:

<tr data-id='@SomeRazorDataId' class="MyAction">foo</tr>

And then:

进而:

$(document).ready(function(){
    $('.MyAction').live("click",function () {
        var id = $(this).attr('data-id');
        window.location = "Customer/Details/" + id;
    })
});

If you are using jQuery 1.7+, you should use the on()method rather than the live()method.

如果您使用的是 jQuery 1.7+,则应该使用on()方法而不是live()方法。

Good luck!

祝你好运!

回答by undefined

There is a typoin your code;

你的代码中有一个错字

success:
//----^

回答by Jo?o Silva

A couple of things:

几件事:

  1. Add a slash(/) between the action and the parameter: url: "Customer/Details/" + id, otherwise, you'll invoke an Actioncalled Details123, for example, which doesn't exist;
  2. Make sure you have a configured routein your Global.asax to support the id, i.e., Customer/Details/{id}:
  3. Like @undefined said, the name of the callback is success, not succes.
  1. 在操作和参数之间添加一个斜杠( /): url: "Customer/Details/" + id,否则,您将调用一个不存在的Action被调用的Details123
  2. 确保您在 Global.asax 中有一个已配置的路由以支持id,即Customer/Details/{id}
  3. 就像@undefined 所说的,回调的名称是success,而不是succes

Your Global.asaxshould have something along these lines:

Global.asax应该有一些类似的东西:

routes.MapRoute(
  "CustomerDetails",
  "Customer/Details/{id}",
  new { controller = "Customer", action = "Details", id = ""}
);

回答by dougajmcdonald

I had this type of situation lately and opted to use the Ajax helper class:

我最近遇到了这种情况并选择使用 Ajax 助手类:

        @Ajax.ActionLink("Details", "Details", 
        new
        {
            id = Model.Id
        }, null)

In this example it would assume that you want a link saying 'details' and you're already in the Customer controller.

在这个例子中,它会假设您想要一个显示“详细信息”的链接,并且您已经在 Customer 控制器中。

Either way, look at the helper classes if all you want to do is fire a controller action from a link, gives you a bit more strong typing in terms of how to pass/handle the id value etc

无论哪种方式,如果您只想从链接中触发控制器操作,请查看辅助类,在如何传递/处理 id 值等方面为您提供更强大的输入

回答by Dhanasekar

The url that you have tried to call is invalid:

您尝试调用的网址无效:

"Customer/Details" + id,

“客户/详细信息”+ ID,

instead it should be "Customer/Details&id=" + id

相反,它应该是“客户/详细信息&id=”+ id

(OR)

(或者)

use 'data'

使用“数据”

$.ajax({ url: "Customer/Details", data:{id:id}, succes: function () { } });

$.ajax({ url: "Customer/Details", data:{id:id}, succes: function () { } });