简体   繁体   中英

Always error funtion is executing in json ajax in asp.net controller

Java Script:-

function themechange(themeValue) {

    $('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
    $.ajax({
        url: '@Url.Action("ChangeTheme", "Login")',
        type: 'GET',
        dataType: 'json',
        cache: false,
        data: { 'themeValue': themeValue },
        success: function (data) {
           alert(data);
        },
        error: function () {
           alert('Error occured');
        }
   });
}

In LoginContoller.cs:-

[HttpGet]
public JsonResult ChangeTheme(string themeValue)
{
    System.Diagnostics.Debug.WriteLine("======ChangeTheme======");

    Session["theme"] = themeValue;
    String x= "========";
    return Json(x, JsonRequestBehavior.AllowGet);
}

All the suggestion which replied so far are not working. Please give a executable project codes links for ASP.NET MVC Application which applies simple ajax with json for just calling a controller method.

You forget to assign the themeValue which get from HTML page by $('#themeId') also there is a problem you use GET instead of POST .

Try this

function themechange(themeValue) {                    
    var themeValue = $('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
    $.ajax({
         url: '@Url.Action("ChangeTheme", "Login")',
         type: 'POST',
         dataType: 'json',
         cache: false,
         data: { 'themeValue': themeValue },
         success: function (data) {
                alert(data);
         },
         error: function () {
               alert('Error occured');
         }
    });
}


[HttpPost]
public JsonResult ChangeTheme(string themeValue)
{
    System.Diagnostics.Debug.WriteLine("======ChangeTheme======");

    Session["theme"] = themeValue;
    String x= "========";
    return Json(x, JsonRequestBehavior.AllowGet);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM