控制器必须提供JsonResult或重定向到视图 [英] Controller must either provide JsonResult or redirect to view

查看:148
本文介绍了控制器必须提供JsonResult或重定向到视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有standardSubmit的ExtJs表单:false。在提交时,控制器将验证formdata,因为某些验证将在服务器上进行(例如,检查名称是否唯一)。如果提供的实体无效,则向客户端发送JsonResult,通知用户哪些字段无效。完美无瑕如果实体有效,它将被存储在数据库中,并且控制器必须将用户重定向到特定视图。

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.

结果是视图提供的HTML被发送到需要JSON响应的客户端。显然,这不起作用。

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;
        }
    }

我一直在寻找超过8的解决方案几个小时了,有人可以帮我吗?

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

推荐答案

成功属性设置为true 。在AJAX调用的成功处理程序中检查这个,并使用javascript(window.location = indexLink)重定向。

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).

值得注意的是,如果要生成链接服务器端您正在使用Web表单视图引擎,您需要执行此操作以在页面中嵌入脚本变量:

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>" %>

然后,您可以在页面中使用 indexLink

You can then use indexLink in your page.

这篇关于控制器必须提供JsonResult或重定向到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆