I want to fetch data from the database whenever the user selects a value from drop down. For these purpose I have written a block for code, in which a JavaScript function is call whenever a user selects a value from drop down and passes that value to the controller through ajax. Below is the snapshot of the code.
cshtml
@Html.DropDownList("Code", null, htmlAttributes: new { @class = "form-control", @onchange = "fetchData(this.value)" })
JS
<script>
function fetchData(Code) {
$.ajax({
url: '@(Url.Action("fetchCode", "ChargesSetup"))',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'Code':'" + Code + "'}",
contentType: false,
processData: false,
success: function (result) {
console.log(result);
},
error: function (result) {
console.log("E");
}
});
}
</script>
NOTE: I have tried my format for passing data to controller, the value of code inside JavaScript is correct as 'A'. But in controller class is show as
@p__linq__0
. when I hard code the value of code the controller work fine.
Controller
[HttpPost]
public JsonResult fetchData(string Code)
{
IQueryable chargestable = from p in db.chargestable where (p.Code == Code) select p;
return Json(chargestable , JsonRequestBehavior.AllowGet);
}
In JavaScript the value of drop down is exactly same what we want:
but after AJAX call, in controller the value of drop down is change to some thing like @p__linq__0
{SELECT
[Extent1].[area] AS [area]
FROM [dbo].[chargestable] AS [Extent1]
WHERE [Extent1].[Code] = @p__linq__0}
What is problem with my code? How can I resolve this as I need to get the buffer of chargestable
whenever drop down value is selected.
By changing return statement makes no effect because the value of parameter is not set, its always null.
return Json(chargestable.ToList(), JsonRequestBehavior.AllowGet);