locked
How to trigger and run a javascript method when the HttpPost got JsonResult as response RRS feed

  • Question

  • User1094269964 posted

    Hi Friends,

    How to trigger and run a javascript method when the HttpPost got JsonResult as response

    For example:

    Here when the user clicks on the Save button the HttPost calls the public ActionResult Index(ProductModel productModel) method.

    Assuming while we are saving the productModel to database it throws an exception and we want to show that exception or somemessage in the UI in a popup.

    How to do this. Please help

    namespace SampleApplication.Models
    {
        public class ProductModel
        {
            public string ProductName { get; set; }
            public string ProductCategory { get; set; }
            public string ProductDescription { get; set; }
            public string ProductYear { get; set; }
            public HttpPostedFileBase productPhoto { get; set; }
        }
    }
    
    namespace SampleApplication.Controllers
    {
        public class ProductController : Controller
        {
            // GET: Product
            public ActionResult Index(string status)
            {
                ProductModel productmodel = new ProductModel();
                if(!string.IsNullOrEmpty(status))
                {
                    ViewBag.LastSaveStatus = status;
                }
    
                return View(productmodel);
            }
    
            [HttpPost]
            public ActionResult Index(ProductModel productModel)
            {
                ProductModel productmodel = new ProductModel();           
                try
                {
                    //assume here we are trying to save it to database and some exception occurred
                    throw new Exception("DatabaseException");
                    return RedirectToAction("Index", new { status = "Sucess", Message = "Data inserted scuessfully" });
                }
                catch(Exception ex)
                {
                    return Json(new { Sucess = "False", Message = "Error while inserting Data in Database"+","+ex.StackTrace });
                }          
              
             }
    
        }
    }
    
    
    @model SampleApplication.Models.ProductModel
    
    @{
        ViewBag.Title = "Index";
    }
    
    @{
        if (!String.IsNullOrEmpty(ViewBag.LastSaveStatus))
        {
            if (ViewBag.LastSaveStatus == "Sucess")
            {
                <div id="div_status">
                    <span style="color:blue">Data saved sucessfully</span>
                </div>
            }
        }
    
    }
    <h2>Index</h2>
    
    
    @using (Html.BeginForm("Index", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
    @Html.AntiForgeryToken()
    <table>
        <tr>
            <td>
                @Html.Label("ProductName", "ProductName")
            </td>
            <td>
                @Html.TextBoxFor(cust => cust.ProductName)
            </td>
        </tr>
    
        <tr>
            <td>
                @Html.Label("ProductCategory", "ProductCategory")
            </td>Html
            <td>
                @Html.TextBoxFor(cust => cust.ProductCategory)
            </td>
        </tr>
    
        <tr>
            <td>
                @Html.Label("ProductDescription", "ProductDescription")
            </td>
            <td>
                @Html.TextBoxFor(cust => cust.ProductDescription)
            </td>
        </tr>
    
        <tr>
            <td>
                @Html.Label("ProductYear", "ProductYear")
            </td>
            <td>
                @Html.TextBoxFor(cust => cust.ProductYear)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Photo", "Photo")
            </td>
            <td>
               <input type="file" id="productPhoto" name="productPhoto"/>
            </td>
        </tr>
    
        <tr>
            <td>
                <input type="submit" name="btnSumit" value="Save" />
    
            </td>
    
        </tr>
    
    </table>
    }
    
    
    @section Scripts {
        <script>
    
            function response() {
                //how to invoke a javascript function where the action returns json
            }
    
        </script>
    }
    
    
    
    

    Wednesday, July 29, 2020 12:42 PM

Answers

  • User1686398519 posted

    Hi bsurendiran,

    1. I suggest you can use Ajax.BeginForm, it can handle the ajax form submission request on post-back.
    2. After successfully inserting data, you can use "window.location.href" to redirect to a new page.
    3. Remarks:
      • When using "Ajax.BeginForm", you need to add the "jquery.unobtrusive-ajax.min.js" file.
      • You can install Unobtrusive AJAX through NuGet.

    View

    @using (Ajax.BeginForm("Index", "Product",
        new AjaxOptions { HttpMethod = "POST", OnSuccess = "suc" }))
    {
     //The code here has not been modified, so the code is omitted.
    }
    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript">
        function suc(data) {
            alert(data.status);
            alert(data.Message);
    if (data.status == "Sucess") {
    window.location.href="@Url.Action("Index")"
    } } </script>

    Controller

            [HttpPost]
            public ActionResult Index(ProductModel pc)
            {
                ProductModel productmodel1 = new ProductModel();
                try
                {
                    //assume here we are trying to save it to database and some exception occurred
                    throw new Exception("DatabaseException");
                    return Json( new { status = "Sucess", Message = "Data inserted scuessfully" });
                }
                catch (Exception ex)
                {
                    return Json(new {status = "False", Message = "Error while inserting Data in Database" + "," + ex.StackTrace });
                }
            }
    

    Here is the result.

    Best regards,

    Yihui Sun

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 30, 2020 5:38 AM

All replies

  • User-2121988648 posted

    You can store the exception in ViewBag.Errors and return the same View();

    In that View you can add the following code,

    @if(ViewBag.Errors!=null){
    <p>@ViewBag.Errors</p>
    }

    Can that solve your problem ?

    Wednesday, July 29, 2020 12:50 PM
  • User-474980206 posted

    If the browser does a post, the the page is replaced with the response. If the response is json, the browser will display it. But a json response does not support JavaScript. As suggested you need to return html. 

    Wednesday, July 29, 2020 2:25 PM
  • User1686398519 posted

    Hi bsurendiran,

    1. I suggest you can use Ajax.BeginForm, it can handle the ajax form submission request on post-back.
    2. After successfully inserting data, you can use "window.location.href" to redirect to a new page.
    3. Remarks:
      • When using "Ajax.BeginForm", you need to add the "jquery.unobtrusive-ajax.min.js" file.
      • You can install Unobtrusive AJAX through NuGet.

    View

    @using (Ajax.BeginForm("Index", "Product",
        new AjaxOptions { HttpMethod = "POST", OnSuccess = "suc" }))
    {
     //The code here has not been modified, so the code is omitted.
    }
    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript">
        function suc(data) {
            alert(data.status);
            alert(data.Message);
    if (data.status == "Sucess") {
    window.location.href="@Url.Action("Index")"
    } } </script>

    Controller

            [HttpPost]
            public ActionResult Index(ProductModel pc)
            {
                ProductModel productmodel1 = new ProductModel();
                try
                {
                    //assume here we are trying to save it to database and some exception occurred
                    throw new Exception("DatabaseException");
                    return Json( new { status = "Sucess", Message = "Data inserted scuessfully" });
                }
                catch (Exception ex)
                {
                    return Json(new {status = "False", Message = "Error while inserting Data in Database" + "," + ex.StackTrace });
                }
            }
    

    Here is the result.

    Best regards,

    Yihui Sun

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 30, 2020 5:38 AM
  • User1094269964 posted

    Thank you

    Thursday, July 30, 2020 8:29 AM