-1

So Im having an issue with my Json Call to the Controller. Im getting an error "parseerror - Unexpected token <"

my code is as follows in my view:

$("select[name='SelectedProjectStatus']").change(function () {

        var DashboardModel = {
            SelectedProjectStatus: $("select[name='SelectedProjectStatus']").val(),
            Page: 1
        };

        $.ajax({
            url: '@Url.Action("Dashboard", "Dashboard")',
            type: 'POST',
            data: JSON.stringify(DashboardModel),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $('#DashboardResult').replaceWith(data);
            },
            error: function (request, status, err) {
                alert(status);
                alert(err);
            }
        });

    });

and in my controller:

    [HttpPost]
    public ActionResult Dashboard(DashboardModel dashboard)
    {
        var MyProjects = EFProject.Project.Where(x => x.UserID == 1);
        if (dashboard.SelectedProjectStatus != 0)
            MyProjects = MyProjects
                        .Where(x => x.Status == dashboard.SelectedProjectStatus)
                        .OrderByDescending(p => p.AuditingCD)
                        .Skip((dashboard.Page - 1) * PageSize)
                        .Take(PageSize);
        else
            MyProjects = MyProjects
                      .OrderByDescending(p => p.AuditingCD)
                      .Skip((dashboard.Page - 1) * PageSize)
                      .Take(PageSize);

        DashboardModel model = new DashboardModel
        {
            Projects = MyProjects,
            PagingInfo = new PagingInfo
               {
                   CurrentPage = dashboard.Page,
                   ItemsPerPage = PageSize,
                   TotalItems = EFProject.Project.Where(x => x.UserID == 1).Count()
               }
        };
        if (Request.IsAjaxRequest())
        {
            return PartialView("DashboardResult", model);
        }
        else
        {
            return View(model);
        }
    }

The partial view im trying to render only has the following:

@using BidThatProject.Web.Models.NonReusableModels.ProjectManagment
@model DashboardModel
<div id="DashboardResult">

</div>

and the parent view obviously has the div with the same id's. It should work at least by showing in me an empty space, but it seems that its having a problem parsing the data back to the view. It could be that its not reading it as a application/json type? I really have no idea.

Morgan Soren
  • 563
  • 4
  • 14
  • 33

1 Answers1

1

use Json Result and return Json(model);

public JsonResults MyTest(){
    var model = FROM b in Table WHERE b.id == 1 select b;
    return Json(model);
}

$.ajax({
        url: '@Url.Action("Dashboard", "Dashboard")',
        type: 'POST',
        data: {page: 1, selected: $("select[name='SelectedProjectStatus']").val() },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) { // 
            // process the json object into html page
        },
        error: function (request, status, err) {
            alert(status);
            alert(err);
        }
    });

here is an edit, as the blog post is getting a partial view via ajax, not json data via ajax:

public ActionResults MyTest(SearchModel  results){
    var model = FROM b in Table WHERE b.id == 1 select b;
    return PartialView("ViewName",model);
}
// you create a partial view that takes in your model
$.ajax({
    url: '/ajax/MySearch',
    type: 'POST',
    data: $("form").serialize(),        
    success: function (data) { // 
        $("#searchresults").html(data);
    },
    error: function (request, status, err) {
        alert(status);
        alert(err);
    }
});
davethecoder
  • 3,856
  • 4
  • 35
  • 66
  • Well, I am following this page example http://www.infinitedreamers.co.uk/mvc3-ajax-search-tutorial/ and it seems that I need to return a partial view if I dont want to paint the whole html in js. – Morgan Soren Apr 17 '12 at 21:27
  • no offensive to the publisher but i only deal with json and ajax for 70% of the work i do and that blog / tutorial sends you down a crazzzzzyyyyy road. your can use jquery templates if your worried about processing the data, simply make a html page with markers $name$ etc and use the template against the json data, thats the blog re-written to be hours less work – davethecoder Apr 17 '12 at 21:33
  • Hmm, well even though its not the best way to build a search page with ajax, its still weird that i get this error because its been working fine for me in another view. However, at this point, I guess I could try anything else that helps me avoid painting the whole content in js, since the real content, which I didnt post ( I posted the partial view empty), is a bit complex ( many c# foreach's). – Morgan Soren Apr 17 '12 at 21:39
  • i just re-looked at everything and i dont know if its my eyes, but that guy isent actually returning json data, he is returning html and basically doing a long way of saying $("#container").html(data); or am i missing something here – davethecoder Apr 17 '12 at 21:40
  • have amended post as you was not working with json as first thought – davethecoder Apr 17 '12 at 21:46
  • thanks, it worked fine without parsing it to Json, but I'll try to find out why the parse error pops up when I send it as a Json type. – Morgan Soren Apr 17 '12 at 22:39
  • you get a parse error because html is not json, json looks like this: http://www.json.org/js.html hence the error on < that is the opening tag on your html that is returned, as the opening on json should b { or [ you get an error because it expected {/[ and got – davethecoder Apr 18 '12 at 08:08
  • As the guilty party for creating the flawed tutorial - and suffering the rather aggressive and offensive abuse for the mistake from a member of this forum - it would be nice to see a better way of doing it as I am always open to improving my knowledge. – James Culshaw Oct 04 '12 at 10:35