Controller must either provide JsonResult or redirect to view

江枫思渺然 提交于 2020-01-06 20:09:19

问题


I have an ExtJs formpanel with standardSubmit: false. On submit, the controller will validate the formdata since some validation will take place on the server (for example a check if the name is unique). If the provided entity is invalid, a JsonResult is sent to the client to notify the user which fields are invalid. That works perfectly. If the entity is valid, it will be stored in the database and the controller must redirect the user to a specific view.

The result is that the HTML provided by the view is sent to the client which expects a JSON-response. Obviously, this does not work.

public override ActionResult Create(FormCollection formCollection)
    {
        Models.Relatie relatie = Repository.CreateNew();
        SetFormValues(relatie, formCollection);

        if (ModelState.IsValid)
        {
            _relatieService.CreateRelation(relatie);
            ViewResult view = View("Index");
            return view; //pumps html while client expects JSON
        }
        else
        {
            JsonResult json = Json(new { success = false, errors = ModelState.ToDictionary() });
            return json;
        }
    }

I've been looking for a solution for over 8 hours now, can anybody please help me out?


回答1:


Send back a JSON object with the success property set to true. Check this in your success handler on the AJAX call and redirect using javascript ( window.location = indexLink).

Worth noting that if you want to generate the link server-side and you're using the web forms view engine you will need to do something like this to embed a script variable in the page:

<%= "<script language=\"javascript\"> var indexLink = \"" + Url.Action("Index") + "\";</script>" %>

You can then use indexLink in your page.



来源:https://stackoverflow.com/questions/5579860/controller-must-either-provide-jsonresult-or-redirect-to-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!