Okay please help, I've been frustrated with this issue.
I need to either set an error value or perform a redirect when a user hits the submit button. (its a standard login form). I need to do it with ajax.
I think its almost working, however when the user clicks submit the page just displays: {"redirect":"/Home/Index"}
or {"error":"The user name or password provided is incorrect."}
its not redirecting/displaying the error how I'm intending it to.
some background - the form is a login form, and its placed inside a modal popup dialog.(jqueryui)
Heres my jquery:
$("#submit").click(function () {
$.post({
url: "Account/LogOn",
dataType: "json",
success: function (data) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error").replaceWith(data.error);
}
}
});
return false;
});
and heres my Action method:
[HttpPost]
public JsonResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Json(new { redirect = returnUrl });
}
else
开发者_StackOverflow {
return Json(new { redirect = "/Home/Index" });
}
}
}
return Json(new { error = "The user name or password provided is incorrect." });
}
heres is my form:
@using (Html.BeginForm("LogOn", "Account"))
{
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
<p>
<input id="submit" type="submit" value="Log On" />
</p>
</fieldset>
</div>
}
Ouch, the whole $.post()-call is wrong.
Use this:
$("#submit").click(function (e) {e.preventDefault();
$.post( "Account/LogOn",
$(this.form).serialize(),
function (data)
{
if (data.redirect)
{
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else
{
// data.form contains the HTML for the replacement form
$("#error").replaceWith(data.error);
}
},
'json'
);
return false;
});
You've used the notation of the arguments like expected in $.ajax() , but in $.post() it's different.
精彩评论