Ajax.BeginForm returns the result and displays the relevant data
I have a page like this:
<% using (Ajax.BeginForm("AddAnswer","Marketplace",new AjaxOptions() {HttpMethod = "POST" })){ %>
Act AddAnswer
adds some data to db. What I want to do is this, when the response has been successfully added, add a #answers
div with the current response passed to the controller. When the response was not successfully added to the db - I would like to display the corresponding error in the #errors
div. How can i do this?
a source to share
Here's what I can suggest:
Controller:
[HttpPost]
public ActionResult AddAnswer(string Value)
{
// TODO: Try to insert the answer value into the database
// and return a JSON object that contains the attempted value
// and an error message if necessary
return Json(new { Answer = Value, ErrorMessage = "" });
}
View:
<% using (Ajax.BeginForm("AddAnswer", "Home",
new AjaxOptions { HttpMethod = "POST", OnSuccess = "success" })) { %>
<%= Html.TextBoxFor(x => x.Value) %>
<input type="submit" value="Add answer" />
<% } %>
<div id="errors"></div>
<div id="answers"></div>
<script type="text/javascript">
function success(arg) {
var obj = arg.get_response().get_object();
// I apologize for the ugliness that follows, I don't know MS Ajax
// but this might written better:
if (obj.ErrorMessage === '') {
var answer = document.createElement('div');
answer.appendChild(document.createTextNode(obj.Answer));
document.getElementById('answers').appendChild(answer);
} else {
document.getElementById('errors').innerHTML = obj.ErrorMessage;
}
}
</script>
a source to share
I wanted to add a comment to Darin, but for some reason I can't. Basically the OnSuccess and OnFailure events DO NOT validate the model, they just confirm that the AJAX call was successful and it went to the controller and it returned without any errors. So if you want to send error messages from the controller, you need to do it as Darin said by sending a json object and handling it in the onSuccess event. You can actually send the <string> list with errors and generate the HTML list in javascript later or whatever you need.
a source to share