简体   繁体   中英

500 error coming when I run my ajax function

I am new to MVC and trying out the ajax functionality on my website. Whenever, I run my ajax function it returns 500 in alert. This is my controller code

[HttpPost]
public ActionResult JsonNewsfeed(int id)
{
    var db = new dekhosaleEntities1();
    sale s = db.sales.First(m => m.sale_id == id);
    List<sale> sale1 = db.sales.ToList();
    saleviewmodel model = new saleviewmodel
    {
        currentsale = s,
        Sales = sale1
    };
    return Json(model);  
}

This is my Jquery ajax function

$('.b1').click(function () {
    $.ajax({      
        type: "POST",
        dataType: 'json',
        url: '@Url.Action("JsonNewsfeed", "Home")',
        data:"{ id: 5}", 
        success: function (data) {
            alert(data);  
        },
        error: function (response) {
            alert(response.status);  
        }
    }); 
});

Try to correct you ajax request ... like URL...(url: 'Url.Action("JsonNewsfeed", "Home")')
data (data: {id:id}) (if needed check that too)

here is the reference..

Documentation: http://api.jquery.com/jquery.ajax/

public ActionResult JsonNewsfeed(int id)
{
    try 
    {
      ....logic here....
      return Json(data, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        //TODO: log exception
        return new HttpStatusCodeResult(401, ex.Message);
    }
}

you could also return like this instead:

return Content(jsonObject.ToString(), "application/json");

or

return Content("Your message",...

Then in your ajax call change the success to:

 $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "/someDir/someAjaxControllerMethod",
        data: jStr,
        success: function (json) {
            ...do something...
            var s = JSON.stringify(json);
            alert(s);
        },
        error: function (event) {
            alert(event.statusText);
        }
    });

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