Can't send parameter with @ViewData["Param"]

54 views Asked by At

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

There are 2 answers

3
sina_Islam On BEST ANSWER

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)
{
...........
}
1
Ruikai Feng On

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