I am working on a .NET Core MVC application, I have added JavaScript code in a partial view, the JavaScript code is hitting function of controller but it is not hitting success function of Ajax call.
Below is my JavaScript code, code is executing on page load
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
type: 'GET',
url: '@Url.Action("getMenurights","Home")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: OnSuccessMenuRights,
failure: function (data) {
alert(data);
}
});
});
</script>
controller code:-
public string getMenuRights()
{
string result = "";
if (!string.IsNullOrEmpty(HttpContext.Session.GetString("UserId")as string))
{
Home objHome = new Home();
DataTable dtMenuRights = new DataTable();
dtMenuRights = objHome.GetMenuRights(HttpContext.Session.GetString("UserId").ToString());
List<DataRow> MenuList = dtMenuRights.AsEnumerable().ToList();
TempData["MenuRights"] = dtMenuRights;
if (MenuList.Count > 0)
{
ViewBag.MenuList = MenuList;
}
TempData.Keep("MenuRights");
//var x = TempData["MenuRights"];
JsonSerializerSettings jss =
new JsonSerializerSettings { ReferenceLoopHandling =ReferenceLoopHandling.Ignore };
result = JsonConvert.SerializeObject(dtMenuRights, Formatting.Indented, jss);
}
return result;
}
2
Answers
Try these
You’re returning empty string if user has no session.
jQuery
, as of 1.9, rejects empty responses. The response should benull
or{}
, not empty string. It also rejects malformedJSON
but unlikely in this case since you’re using a library to generateJSON
.It could be because your return type is
string
, thusContent-Type
header becomestext/plain
. Try using either one of thesedataType: 'text json'
in yourjQuery
call. This will tell jQuery to treat text asJSON
.JSON
instead ofstring
from the MVC controller usingJsonResult
as your return type. This should causeContent-Type
header to be set toapplication/json
.Here is the spec in details (see
dataType
)https://api.jquery.com/Jquery.ajax/
Based on your code, we can find that your action method
getMenuRights()
return a plain text string to consumer, you can modify thedataType
option to'text'
, like below.Besides, to troubleshoot Ajax request related issue, you can try to check the response of that ajax request you made in browser F12 developer tool Network tab. And check if something wrong with the request you made (http 400 error) or server side (http 500 error) etc.