Srujan Chowdary Panda
Srujan Chowdary Panda

Reputation: 1339

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

I'm new to 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.
  2. I made an ajax call to pass the parameters from my view to the controller.

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.

Please let me know if I'm missing anything.

Thanks in advance.

Upvotes: 1

Views: 11256

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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:

$(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(){
            }
        });
 });

Upvotes: 0

Mads...
Mads...

Reputation: 391

$(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.

Upvotes: 1

Mads...
Mads...

Reputation: 391

Please check with the arguments your Action method is accepting.

for example if signature is

public ActionResult Action1(string name)

then you need to pass the data as

var data = { name :  $("txtinPartialView").val() }

Upvotes: 1

Related Questions