How can I return a JSON result to a Ajax.BeginForm

43,780

Solution 1

you need to include jquery.unobtrusive-ajax.js file.

<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

Solution 2

JsonResult is just a kind of ActionResult derived class that indicates that this action will return JSON instead of a view or something else.

For example:

 @using (Ajax.BeginForm("CreateProductFromAjaxForm","Product" , null, 
              new AjaxOptions() {  OnSuccess = "getresult" }, null))

This will generate a element which will send an AJAX request when submitted to the action. For this to work you need to include the following script to your page:

Now all that's left is to write this onSuccess javascript function and process the JSON results returned by the server:

<script type="text/javascript">
var onSuccess = function(data) {
    alert(data.result);
};
</script

Solution 3

in page

new AjaxOptions() {  
    OnSuccess = "getresult", 
}

in javascript

function getresult(data){
   alert(data.x);
}

in c#

[HttpPost]
public ActionResult CreateProductFromAjaxForm(CreateProductModel model)
{
    if (!ModelState.IsValid)
    {
        return Json("error", JsonRequestBehavior.AllowGet);
    }

   //add to database

    return Json(model, JsonRequestBehavior.AllowGet);
} 

Solution 4

Try specifying the HTTP method:

new AjaxOptions() {  
    OnSuccess = "getresult", 
    HttpMethod = "post" 
}

Example:

@using (Ajax.BeginForm("CreateProductFromAjaxForm", "Product" , null, new AjaxOptions() {  OnSuccess = "getresult", HttpMethod = "post" }, null))
{
    ....
}

Solution 5

I faced the same issue with my project. Ajax library is not being loaded is the problem. When I checked my bundleconfig and my layout file, it did have the include but I'm including the absolute name for ajax library like

bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.min.js"));

My friend asked me to use the wild card instead. Surprisingly bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include("~/Scripts/jquery.unobtrusive-ajax*")); started including the ajax library.

Now my OnSuccess functions are loading as expected rather than looking at the blank screen with json response on it.

Share:
43,780
Stefan
Author by

Stefan

The mystery of life isn't a problem to solve, but a reality to experience. ― Frank Herbert, Dune

Updated on September 20, 2020

Comments

  • Stefan
    Stefan over 3 years

    I have got this simple form:

    @using (Ajax.BeginForm("CreateProductFromAjaxForm","Product" , 
                      null, 
                      new AjaxOptions() {  HttpMethod = "post", OnSuccess = "getresult" },
                      null))
    {
        @Html.EditorFor(m => m)
        <hr />
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-info" value="Next" />
            </div>
        </div>
    }  
    

    And, for testing, a simple controller:

        [HttpPost]
        public JsonResult CreateProductFromAjaxForm(CreateProductModel model)
        {
            if (!ModelState.IsValid)
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "error" }
                };
            }
    
           //add to database
    
            return new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new { result = "success"}
            };
        }  
    

    I have added these to the Web.Config:

     <add key="ClientValidationEnabled" value="true" />
     <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    

    and these to my script bundle:

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/jquery.validate.js",
                        "~/Scripts/jquery.validate.unobtrusive.js"
                        ));
    

    After clicking the "Submit" button, the resulting page just shows:

    {"result":"success"}
    

    I would expect that I could handle the result in the OnSuccess="getresult" handler, but it doesn't seem to work.

    Basically I am using the Ajax.BeginForm mainly for the clientside validation.

    Can you tell me whats wrong?

    UPDATE: I added the HttpMethod = "post" to the AjaxOptions.

    UPDATE: The getresult, is defined above the Ajax.BeginForm like this:

    <script type="text/javascript">
        var getresult = function (data) {
            alert(data.result);
        };
    </script> 
    
    • Rui Jarimba
      Rui Jarimba over 10 years
      Can you post the definition of your getresult method?
    • Rui Jarimba
      Rui Jarimba over 10 years
      Put a dummy alert inside the javascript function, just to see if it is being invoked, something like: alert('hello')
    • Stefan
      Stefan over 10 years
      @RuiJarimba: no luck with the alert('hi'); either.
  • Stefan
    Stefan over 10 years
    Unfortunately; no difference.
  • Stefan
    Stefan over 10 years
    Again; no success. I even tried to omit the data parameter: same result.
  • Stefan
    Stefan over 10 years
    I don't have this in my script directory. I am using MVC 5. Should I download it?
  • Lin
    Lin over 10 years
    Yes, use NuGet Packages to find Microsoft jQuery Unobtrusive Ajax.
  • Aswin Arshad
    Aswin Arshad over 6 years
    Life saver in 2017