I'm trying to use Ajax.BeginForm features.
The form is posted correctly, but I need to retrieve data in json format, from my controller action and refresh a div with the operation result message.
I have found several suggestions here in Stackoverflow, but none is useful.
Here is a suggestion found:
var data = content.get_response().get_object();
But it didn't work for me. And I believe is deprecated up today, functional only for MVC 2 and lower versions. My current MVC version is 3.
Here is a piece of code:
<script type="text/javascript">
function fnCompleted(data){
if(data.Success)
$("#somediv").html(data.StatusMessage).addClass("success");
else
$("#somediv").html(data.StatusMessage).addClass("error");
}
</script>
@{
var ajaxOptions= new AjaxOptions{
OnComplete= "fnCompleted",
Url= '@Url.Action("myAction", "myController")',
Method= "POST"
}
<div id="somediv">/*Here goes the json response*/</div>
using(Ajax.BeginForm(ajaxOptions)){
@Html.EditorForModel()
<input type="submit" name="send" value="Send">
}
Here is a piece of my controller action:
[HttpPost]
public JsonResult myAction(MyModel mymodel)
{
try
{
if (myModel== null)
throw new Exception("The model is empty");
if (!ModelState.IsValid)
throw new Exception("The model is wrong");
var found = /*Look for existence of the model in the database*/;
if(found)
throw new Exception("Already exists the object");
/*Operation with the database*/
var result = Json(
new
{
Success = true,//success
StatusMessage = "Object created successfully"
});
return result;
}
catch (Exception exception)
{
var result = Json(
new
{
Success = false,//error
StatusMessage = exception.Message
});
return result;
}
}