控制器必须提供 JsonResult 或重定向到视图
我有一个带有 standardSubmit: false 的 ExtJs 表单面板。提交时,控制器将验证表单数据,因为服务器上会进行一些验证(例如检查名称是否唯一)。如果提供的实体无效,则会将 JsonResult 发送到客户端以通知用户哪些字段无效。效果很好。如果实体有效,它将存储在数据库中,并且控制器必须将用户重定向到特定视图。
结果是视图提供的 HTML 被发送到需要 JSON 响应的客户端。显然,这是行不通的。
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发送回一个 JSON 对象,并将
success
属性设置为 true。在 AJAX 调用的成功处理程序中检查这一点,并使用 javascript (window.location = indexLink) 进行重定向。值得注意的是,如果您想在服务器端生成链接并且正在使用 Web 表单视图引擎,则需要执行类似以下操作以在页面中嵌入脚本变量:
然后您可以使用
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).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:
You can then use
indexLink
in your page.