Reputation: 1782
I am using jQuery Ajax, and I hit the success: function (msg)...
. I want to be able to specify when to hit: error: function (msg)...
The issue here seems to be that I don't have a way to return true
or false
, since I have to return a View. In a normal web app (unlike mvc), I used to just return true or false, then I could check on this boolean value, and act according to this.
How can I specify that I want to jump to the error: function (msg)
in some cases? For example when the validation doesn't pass, I don't want it to say it's a success.
Here is my JQuery code:
function ContactDialog(action, controller) {
var url = '/' + action + '/' + controller;
$("#ContactDialog").dialog({
autoOpen: true,
hide: "fade",
show: "bounce",
height: $(window).height() / 2,
width: $(window).width() / 2,
title: "Send an email",
buttons: [{
text: "Send", click: function () {
$.ajax({
url: url,
data: $("form").serialize(),
context: this,
contentType: 'application/html; charset=utf-8',
dataType: "html",
success: function (msg) {
$(this).dialog("close");
sendConfirmMessage('msgSent');
},
error: function (data) {
sendConfirmMessage('msgNotSent');
}
});
},
}, {
text: "Cancel", click: function () {
$(this).dialog("close");
}
}]
});
} And my html code that does the validation:
<div id="ContactDialog" style="display: none;">
@using (Ajax.BeginForm(null, null, new AjaxOptions { UpdateTargetId = "UpdaterDiv" }, new { id = "contactForm" }))
{
@Html.LabelFor(model => model.subject)
@Html.TextBoxFor(model => model.subject, new { @class = "AboutControls" })
<br />
@Html.ValidationMessageFor(model => model.subject)
<br />
@Html.LabelFor(model => model.from)
@Html.TextBoxFor(model => model.from, new { @class = "AboutControls" })
<br />
@Html.ValidationMessageFor(model => model.from)
<br />
@Html.LabelFor(model => model.body)
@Html.TextAreaFor(model => model.body, new { @class = "AboutControls AboutControlTxtArea" })
<br />
@Html.ValidationMessageFor(model => model.body)
<hr />
<br /><br />
}
</div>
Here is the code where I am forced to return a View:
public PartialViewResult SendMail(EmailModel model)
{
if (ModelState.IsValid)
{
mailMsg = new MailMessage(model.from, receiver, model.subject, model.body);
smtp.Send(mailMsg);
return PartialView("_About");
}...
The jQuery Ajax code has no way of knowing when it is a success or failure from the above code, since I can't say return true
or return false
Hope I am making myself clear
Upvotes: 0
Views: 40
Reputation: 1223
In your MVC controller action do the following:
var status = new HttpStatusCode();
if(DataIsInvalid) //whatever validation you need to perform
{
status = HttpStatusCode.BadRequest;
}
// any other validation
return new HttpStatusCodeResult(status);
If you need to change it back so it doesn't trigger the error
in your AJAX, either leave status
null or set it to HttpStatusCode.OK
Upvotes: 1