Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am working with a .net core web project. I have to send a value from javascript to razor pageModel. But the problem is I can't get value from pageModel in JSON format. It returns the source code of whole cshtml page. I have tried each and every solution I found. Here is what I have tried recently

What I have tried:

AJAX
JQuery
$.ajax({
    type: "POST",
    url: '/index?handler=RetData',
    headers: {
        Accept: "application/json; charset=utf-8"
    },
    beforeSend: function (xhr) {
        xhr.overrideMimeType("application/json; charset=utf-8")
    },
    data: AddAntiForgeryToken({ 'oldEmail': oldEmail }),
    dataType: "json",
    success: function (retValue) {
        alert(retValue);
    },
    error: function (e) {
        var msg = "Error!" + e.message;
        alert(msg);
    }
});


index.cshtm.cs Code:

C#
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult OnPostRetData([FromBody] JObject jobject)
{
    try
    {
        JObject job = new JObject();
        job.Add("Album", "Me Against The World");
        return new JsonResult(job);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
Posted
Comments
F-ES Sitecore 16-Sep-19 10:42am    
You are requesting the "Index" action in your ajax, that is why you're getting the page html back.
Muhammad Afaq Riaz 16-Sep-19 14:19pm    
Then what should I use?
F-ES Sitecore 17-Sep-19 5:11am    
I assume you want to call OnPostRetData so it is the path to that. If your js is on a razor view you can use

url: '@Url.Action("OnPostRetData", "Controllername")',

if it's in a js file then the easiest way is to hard-code, it will probably be

/controllername/OnPostRetData

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900