views:

37

answers:

2

I have the following code in my view:

 <% using (Ajax.BeginForm("JsonCreate", new AjaxOptions { OnComplete = "createCategoryComplete" }))


  { %><div id="createCategory">
        <fieldset>
            <legend>Add new category</legend>
            <p>

<%=Html.TextBox("CategoryId")%>
<%=Html.TextBox("Test")%>
            <label for="name">Name:</label>
            <%= Html.TextBox("Name")%>
            <%= Html.ValidationMessage("Name")%>

        </p>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
</div>

<% } %>

In the controller the code is as follows:

[AcceptVerbs(HttpVerbs.Post)]
    public JsonResult JsonCreate(string Name)
    {
        if (ModelState.IsValid)
        {
            try
            {


                //Return a json object to the javascript
                return Json(new { CategoryId = 123, Test= "test successful" });
            }
            catch
            {
                #region Log errors about the exception
                //Log error to administrator here
                #endregion
            }
        }

        //If we got this far, something failed, return an empty json object
        return Json(new { /* Empty object */ });
    }

What should be the code in the view for the following function to read the values returned by the Json and update the textboxes for CategoryId and Test?

  function createCategoryComplete() {....???}
A: 

Try this,

success: function(data) {
         alert(data.CategoryId + " " + data.Test);

EDIT:

function createCategoryComplete(data)
{
   document.getElementById("UrTxtBoxID").value = data.Test;
}
Pandiya Chendur
where should I write this? How can I update the textboxes with the values of data.CategoryId and data.Test?
A: 
function createCategoryComplete(e) {
    var obj = e.get_object();
    alert(obj.CategoryId + ' ' + obj.Test);
}
Darin Dimitrov
It`s not displaying the alert, rather giving me a dialog to save the json values
That's probably because you have a javascript error in your page and the AJAX call is not being executed. Did you include the `MicrosoftAjax.js` and `MicrosoftMvcAjax.js` scripts to your page?
Darin Dimitrov
Thank you. That has solved my problem. How can I display modelstate errors returned by Json ?What if i`m doing the following:ModelState.AddModelError("_FORM", "Username or password is incorrect.");return Json(new { ModelState});What must be my code in the view then?