【发布时间】:2011-03-02 07:21:55
【问题描述】:
我正在使用 Razor 创建一个新项目 asp.net mvc3,并希望将 LogOn 转换为 ajax 请求。
HTML
@using (Ajax.BeginForm("LogOn", "Account", new AjaxOptions { HttpMethod="post", OnSuccess="LoginSubmitted"}))
{
}
控制器
if (Request.IsAjaxRequest())
{
return Json(new { ResultMessage = "Username or password provided is incorrect"});
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
其他一切都保持不变。
首先,查看 Fiddler 的 http 响应,我注意到没有 x-requested-with 标头。所以我加了
<input type="hidden" name="X-Requested-With" value="XMLHttpRequest" />
这似乎可行,但现在我收到的是一个 Json 对象,它没有被解析,而是 Google Chrome 只是通过发送回一个应用程序/json 文档来将 Json 呈现到屏幕上。所有脚本都已到位。
我也这样做了:
@using (Ajax.BeginForm("Submit", "home", new AjaxOptions { HttpMethod = "Post", OnSuccess="LoginSubmitted"}))
{
}
@section head
{
<script type="text/javascript">
function LoginSubmitted(res) {
alert(res.Message);
}
</script>
}
public ActionResult Submit(string id)
{
if (Request.IsAjaxRequest())
{
return Json(new { Message = "Logged In" } );
}
else
{
return View();
}
}
我自己创造的一种形式,使用标准助手可以正常工作。
发生了什么事?
【问题讨论】:
标签: asp.net ajax json asp.net-mvc-3 razor