I am working on a validation routine that needs to go back to the server, perform a bit of database checking and then return to the client to display messages depending on the outcome.. I am using MVC3, Javascript, Ajax.
This is my clientside:
<script type="text/javascript">
$('#usrid').change(function (e) {
var formData = $("form").serialize();
$.ajax({
url: "ValidateOfficers",
type: "POST",
data: formData,
success: function (data) {
alert(data.reponseText);
},
error: function (data) {
alert(data.reponseText);
}
});
});
This is my controller action:
[HttpPost, ActionName("ValidateOfficers")]
public ActionResult ValidateOfficers(userRole role)
{
int holderid = role.holderid;
int roleSelected = role.roleid;
int chosenUser = role.usrid;
int countRoles = db.userRoles.Where(i => i.roleid == roleSelected && i.holderid == holderid).Count();
if (countRoles == 0) //success:
{
Response.StatusCode = 200;
Response.Write("ok");
return View("Create", role);
}
if (countRoles > 0) //error:
{
Response.StatusCode = 500;
Response.Write("error");
return View("Create", role);
}
return View();
}
What I want to do perform the count and then send back a status based on the count result.. So if countRoles = 1 then return text “officer exists” if countRoles > 1 then “duplicate records exist”. if countRoles is zero then I can assume success and offer no message.
Ok, I am stuck on how to built this custom message on the server side and how to post it back to the client. I was thinking of adding a couple of labels to the razor and show/hiding depending on the count result.. As you can see I have had a very basic go, but to no avail. I get “undefined” in the alert messages currently.
If I can get some tips on this I would be most grateful!!
Action
Javascript
and you also would want to read this article, for knowing how to return json data.
Hope this solves your problem.