skip to Main Content

I need help, i can’t send parameter from ViewData in javascript to Controller, maybe because in controller using JsonResult, but I haven’t found the solution till now, is there any way to fix it ?

this my js :

var urlString2 = "@Url.Action("GetAttributeLabel", "MasterDataTemp")?modifierId=@ViewData["ModifierId"]";
$.ajax({
   url: urlString2,
   type: "GET",
   dataType: "json",
   contentType: 'application/json; charset=utf-8',
        async: true,
        processData: false,
        cache: false,
        success: function (data) {
     $.each(data, function (i, item) {
        dataAttributeLabel.push(item.AttributeName);
    });
   },
    error: function (xhr) {
       alert('error');
   }
});

this is my controller :

public JsonResult GetAttributeLabel(Guid modifierId)
{
...........
}

The parameter always send empty guid, please help..

2

Answers


  1. Please try like below

    @{
     string guid = ViewData["ModifierId"].ToString();
    }
    var urlString2 = "MasterDataTemp/GetAttributeLabel?modifierId="+"@guid";
    
    $.ajax({
       url: urlString2,
       type: "GET",
       dataType: "json",
       success: function (data) {
         $.each(data, function (i, item) {
            dataAttributeLabel.push(item.AttributeName);
        });
       },
        error: function (xhr) {
           alert('error');
       }
    });
    

    And at controller

    public JsonResult GetAttributeLabel(string modifierId)
    {
    ...........
    }
    
    Login or Signup to reply.
  2. Firstly, you have to avoid sending JSON data with jQuery Ajax GET request, if you do want to send JSON data, try with a POST request.

    Secondly, you could generate the url in @Section like this:

    @{        
        string val = ViewData["key"] != null ? ViewData["key"].ToString()
                                             : "defaultval"; 
           
        var routedic = new Dictionary<string, string>()
                           {
                               { "key", val }
                           }; 
           
        var url = Url.Action("Test", "Home", routedic);
    } 
    

    And then send the request:

    <script>    
      var urlstr="@(url)";
      // check the uri in console  
      console.log(urlstr);   
     $.ajax({       
       url:urlstr,        
       type:"GET"    
    });
    </script>
    

    It works well now:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search