如何返回 JSON 或 RedirectToAction?
我有一个操作方法,我想在一个条件下返回 JSON,或者在另一个条件下重定向。我认为我可以通过从我的方法返回 ActionResult 来做到这一点,但这样做会导致错误“并非所有代码路径都返回值”
有人能告诉我我做错了什么吗?或者说怎样才能达到想要的效果呢?
下面是代码:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(User user)
{
var myErrors = new Dictionary<string, string>();
try
{
if (ModelState.IsValid)
{
if (userRepository.ValidUser(user))
{
RedirectToAction("Index", "Group");
//return Json("Valid");
}
else
{
return Json("Invalid");
}
}
else
{
foreach (KeyValuePair<string, ModelState> keyValuePair in ViewData.ModelState)
{
if (keyValuePair.Value.Errors.Count > 0)
{
List<string> errors = new List<string>();
myErrors.Add(keyValuePair.Key, keyValuePair.Value.Errors[0].ErrorMessage);
}
}
return Json(myErrors);
}
}
catch (Exception)
{
return Json("Invalid");
}
}
编辑:澄清一下,我已经尝试按照答案中的建议返回 RedirectToAction("Index", "Group"); 但它没有什么都不做。我重定向到的操作中的断点没有被击中。
I have an Action Method that I'd either like to return JSON from on one condition or redirect on another condition. I thought that I could do this by returning ActionResult from my method but doing this causes the error "not all code paths return a value"
Can anyone tell me what I'm doing wrong? Or how to achieve the desired result?
Here's the code below:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(User user)
{
var myErrors = new Dictionary<string, string>();
try
{
if (ModelState.IsValid)
{
if (userRepository.ValidUser(user))
{
RedirectToAction("Index", "Group");
//return Json("Valid");
}
else
{
return Json("Invalid");
}
}
else
{
foreach (KeyValuePair<string, ModelState> keyValuePair in ViewData.ModelState)
{
if (keyValuePair.Value.Errors.Count > 0)
{
List<string> errors = new List<string>();
myErrors.Add(keyValuePair.Key, keyValuePair.Value.Errors[0].ErrorMessage);
}
}
return Json(myErrors);
}
}
catch (Exception)
{
return Json("Invalid");
}
}
Edit: to clarify, I've already tried to return RedirectToAction("Index", "Group");
as suggested in the answers but it doesn't do anything. The breakpoint in the action I'm redirecting to doesn't get hit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你需要更改
为
You need to change
to
你应该返回RedirectResult。将此字符串更改
为
,一切都会正常工作。
you shold return RedirectResult. Change this string
to
and all will work fine.
您缺少返回语句:
Controller.RedirectToAction
< /a> 方法返回一个RedirectToRouteResult
并且Controller.Json
方法返回 <代码>JsonResult。两者都扩展了 ActionResult。Your missing a return statement:
The
Controller.RedirectToAction
method returns aRedirectToRouteResult
andController.Json
method returns aJsonResult
. Both extendActionResult
.我认为您的重定向没有到达您想要的位置的原因是它指向一个仅接受 Gets 的操作,而您正在重定向一个 Post。
I think the reason your redirect is not getting where you want is that it is directing to an action that accepts only Gets and you are redirecting a Post.