Neel Darji
Neel Darji

Reputation: 143

How to Pass value from view to another controller in MVC ASP .NET

I want to pass selected index of dropdownlist in View to a different controller. I use java script for getting index of dropdaownlist. I got the Index.

But I want to pass that index to another Controller on click of my button .

How can I do that ?

here is my Java script snnipet

  $('#btnsubmit').click(function () {

        var deviceid = $('#ddldevice option:selected').val();

        $.ajax({
            type: 'GET',
            data: { deviceid: deviceid },
            url: '@Url.Action("ViewSensorTable","Home")',
            success: function (result) {


            }

        });

My Button Code

 <input type="submit" id="btnsubmit" value="Next" class="btn btn-primary btn-sm" />

And here is the Controller where i want the index value

 public ActionResult ViewSensorTable(int id)
 {
     return View();
 }

Edited

$('#btnsubmit').click(function () {

    var deviceid = $('#ddldevice option:selected').val();

    $.ajax({
        type: 'GET',
        data: { id: deviceid },
        url: '@Url.Action("ViewSensorTable","Home")',
        success: function (result) {


        }

    });

Upvotes: 2

Views: 2704

Answers (2)

Sahil Sharma
Sahil Sharma

Reputation: 1899

You need to pass deviceid with the ajax request. Also the parameter name in Action Method should match with the parameter you are sending using ajax. Try the below code:

View

    <input type="submit" id="btnsubmit" value="Next" class="btn btn-primary btn-sm" />

    $('#btnsubmit').click(function () {

        var deviceid = $('#ddldevice option:selected').val();
        alert(deviceid);  //Comment it after testing

        $.ajax({
            type: 'GET',
            data: { id: deviceid },
            dataType: "json",
            url: '@Url.Action("ViewSensorTable","Home")',
            success: function (result) {
               //do something with the result
            }
        });
}

Controller

[HttpGet]
public ActionResult ViewSensorTable(int id)
 {
     return View();
 }

Upvotes: 1

Karan
Karan

Reputation: 12619

Try replacing your URL as

url: '@Url.Action("ViewSensorTable","Home")' + '/' + deviceid,

Or If your Action is [HTTPPost] then you need to change,

type: 'POST',

Upvotes: 0

Related Questions