views:

44

answers:

1

I have a from on my page as follows:

    <% using (Ajax.BeginForm("AddAnswer","Marketplace",new AjaxOptions() 
{HttpMethod = "POST" })){ %>

AddAnswer action adds some data to db. What I want to do is: when answer has been successfully added, append #answers div with the current answer passed to controller. When answer has not been successfully added to db - I would like to display appropriate error in #errors div. How can I do this?

+1  A: 

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>
Darin Dimitrov