2

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) {


        }

    });
Neel Darji
  • 143
  • 3
  • 15
  • 2
    `data: { id: deviceid }` - the name of the parameter you send to the server must match the name of the parameter the server is expecting. Otherwise it cannot map it. Also you can simplify `$('#ddldevice option:selected').val();` to `$('#ddldevice').val();` - jQuery will get the value of the selected option automatically. – ADyson Jun 29 '18 at 08:57
  • @ADyson I do that , I got it but now one more error occur . The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult ViewSensorTable(Int32)' in 'CalReport.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters – Neel Darji Jun 29 '18 at 09:01
  • 1
    @NeelDarji Check what `deviceid` is when you make your AJAX call. – IronAces Jun 29 '18 at 09:03
  • @NeelDarji I would guess in that case that `deviceid` is null, and therefore you send an empty value to the server. Of course in your action method, `id` is not allowed to be null. Do some simple debugging in your JavaScript to check what is happening. – ADyson Jun 29 '18 at 09:05
  • @NeelDarji check with console.log(deviceid ) before the ajax's request which value it got. On server side you can set the attribute with decorate [DisplayFormat(ConvertEmptyStringToNull = false)] for to be sure that the binding don't convert empty string to null value. – Jordi Jordi Jun 29 '18 at 09:10
  • @Daneil Shillcock how can I check that – Neel Darji Jun 29 '18 at 09:14
  • @NeelDarji Do you understand how to use your browser's Developer Tools (press F12 on most browsers) to do debugging? If not, now would be an excellent time to learn. It gives you access to a Console, Network monitoring tools, JS code (so you can set breakpoints etc like you do in Visual Studio with the C# code), and HTML view. You can debug everything about your page. Checking the value of a single variable as you do is quite trivial - you can either set a breakpoint, or write code to log the value into the console as Jordi showed you – ADyson Jun 29 '18 at 09:49
  • 2
    One other small thing, unrelated but useful: `public ActionResult ViewSensorTable(int id) { return View(); }` -- you should not be returning a whole View here - this will return everything including your Layout page with full HTML tags, head, body etc. This is not helpful when responding to an AJAX request. You should either return a small amount of HTML (via a Partia lView) which can be inserted into your existing full page in the browser, or some JSON data which JavaScript can read and process. You can find examples and tutorials of both designs online very easily. – ADyson Jun 29 '18 at 09:51

2 Answers2

1

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();
 }
Sahil Sharma
  • 1,813
  • 1
  • 16
  • 37
  • The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult ViewSensorTable(Int32)' in 'CalReport.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters – Neel Darji Jun 29 '18 at 09:47
  • 1
    Is there any value in deviceid? – Sahil Sharma Jun 29 '18 at 09:49
  • I dont know ,I am new to MVC. – Neel Darji Jun 29 '18 at 09:58
  • Use the updated code I have mentioned. I have put an alert function in javascript. Check if it pops with value or not. However visit this link to learn about console.log() https://stackoverflow.com/questions/4539253/what-is-console-log – Sahil Sharma Jun 29 '18 at 10:01
  • I write the alert. It popup with my deviceId. but at the end it gives me same error. – Neel Darji Jun 29 '18 at 10:07
  • Have you replaced the whole ajax call with updated code I have written? If not, do it once and check – Sahil Sharma Jun 29 '18 at 10:10
  • Since your button is a "submit" button, it's possible it is submitting the form simultaneously as well as doing the ajax request. Try with `$('#btnsubmit').click(function (event) { event.preventDefault(); //..then continue the rest of your submit handler` . See https://api.jquery.com/event.preventdefault/ – ADyson Jun 29 '18 at 10:20
  • @SahilSharma for your kind help. I solve it by changing (int id) to (object id). It works fine when I use object instead of int , I don't know why but it don't work with integer in my case. – Neel Darji Jun 29 '18 at 10:27
  • It should work with int as well. No idea where it stuck. :) – Sahil Sharma Jun 29 '18 at 10:30
  • @NeelDarji perhaps you are not sending an int? Maybe it's a decimal, or a string, or something else. Yet again, this hinges on knowing the content of `deviceid` when you send it to the server. You still haven't told us. I explained to you how to debug it in the comments above, on the main question thread. I would avoid accepting an `object` in the server method if you can, it's much harder to validate correct input. Instead try to work out what specific type it should be, by examining your deviceid. – ADyson Jun 29 '18 at 12:20
  • @ADyson ohh sorry for that. I debug as per your suggestion and i got the content of deviceid what I want and it is in ineger. But when I try to pass it , It give me the error, So that I use object as datatype in my contarller. – Neel Darji Jun 29 '18 at 12:23
  • @NeelDarji so it's like `1`,`2`, `3` or something? Not `1.23` or anything like that? I find it hard to believe the server would not accept it as an int, if it really is parseable as one. – ADyson Jun 29 '18 at 12:27
  • @SahilSharma Is there any specific reason you set `traditional: true` in the example above? It should not be necessary - we are only serialising a simple value. This option only affects nested objects AFAIK. Best not to include unnecessary code without explanation. It might make people think it is part of the solution – ADyson Jun 29 '18 at 12:28
  • @ADyson - Exactly my point that server will except the value whether it's string or int. – Sahil Sharma Jun 29 '18 at 12:28
  • 1
    @ADyson I added it for deep objects as a generalized solution while hit and trial. However, you made a good point about confusion if there is only single value. I'll remove it. – Sahil Sharma Jun 29 '18 at 12:32
  • @ADyson the value is like 1 – Neel Darji Jun 29 '18 at 12:37
  • Instead of var deviceid = $('#ddldevice option:selected').val(); if you replace it with var deviceid = '1'; and change the ActionParameter to int from object. Is it working? – Sahil Sharma Jun 29 '18 at 12:38
  • @SahilSharma I used html dropdownlist instead of razor. And If I change var deviceid=$(#ddldevice option:selected').val();) to deviceid = '1' then how can I get current selected index of dropdownlist ? – Neel Darji Jun 29 '18 at 12:51
  • 1
    I'm asking for testing purpose to send the value as simply '1' to check whether the ajax call is working fine or not. – Sahil Sharma Jun 29 '18 at 12:52
0

Try replacing your URL as

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

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

type: 'POST',
Karan
  • 12,059
  • 3
  • 24
  • 40