简体   繁体   English

如何在AVC中使用ajax进行按钮单击来调用Action方法?

[英]How to call an Action method using ajax for a button click which is in partial view in MVC?

I'm new to MVC. 我是MVC的新手。 I got a situation where I need to pass a parameter from view to controller on the button click (the button is in partial view), which then renders another partial view in the same page. 我遇到一种情况,我需要在按钮单击时将参数从视图传递到控制器(按钮在部分视图中),然后在同一页面中呈现另一个部分视图。

Steps followed: 遵循的步骤:

  1. I used jquery button click event for the button of partial view. 我将jquery button click事件用于部分视图的按钮。
  2. I made an ajax call to pass the parameters from my view to the controller. 我进行了ajax调用,以将参数从我的视图传递到控制器。

The following is my code: 以下是我的代码:

$(document).on("click", "#btninPartialView", function(e){
    var data = $("txtinPartialView").val();
    $("#mainPageContainer").load("/Controller/Action", data, function(){
        $.ajax({
            //url: @Url.Action("Action", "Controller"),
            type: GET,
            data: {
                id: data
            },
            success: function(){
            }
            error: function(){
            }
        })
    }    
})

Problem: The problem is that, the data I'm received in the action method is null . 问题:问题是,我在action方法中收到的数据为null

Please let me know if I'm missing anything. 如果我有任何遗漏,请告诉我。

Thanks in advance. 提前致谢。

Please check with the arguments your Action method is accepting. 请检查您的Action方法接受的参数。

for example if signature is 例如,如果签名是

public ActionResult Action1(string name)

then you need to pass the data as 那么您需要将数据传递为

var data = { name :  $("txtinPartialView").val() }
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();

$.ajax({
    url: "/Controller/Action",
    type: GET,
    data: {
        id: data
    },
    success: function(result){
$("#mainPageContainer").html(result);
    }
    error: function(){

})
})

This should work. 这应该工作。

The problem is that you are mixing both jquery ajax and load function, load function sends an ajax call behind the scenes, so you need to use one of them, not both, so try like: 问题是您同时混合了jquery ajax和load函数,load函数在后台发送了ajax调用,因此您需要使用其中之一,而不是两者,因此请尝试:

$(document).on("click", "#btninPartialView", function(e){

        $.ajax({
            url: '@Url.Action("Action", "Controller")',
            type: GET,
            data: {
                id: $("txtinPartialView").val()
            },
            success: function(response){
                $("#mainPageContainer").html(response);
            },
            error: function(){
            }
        });
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM