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>
}
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.
I suggest you can use Ajax.BeginForm, it can handle the ajax form submission request on
post-back.
After successfully inserting data, you can use "window.location.href" to
redirect to a new page.
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
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
4 Points
95 Posts
How to trigger and run a javascript method when the HttpPost got JsonResult as response
Jul 29, 2020 12:42 PM|bsurendiran|LINK
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
Member
30 Points
32 Posts
Re: How to trigger and run a javascript method when the HttpPost got JsonResult as response
Jul 29, 2020 12:50 PM|vsetia|LINK
You can store the exception in ViewBag.Errors and return the same View();
In that View you can add the following code,
Can that solve your problem ?
All-Star
58254 Points
15681 Posts
Re: How to trigger and run a javascript method when the HttpPost got JsonResult as response
Jul 29, 2020 02:25 PM|bruce (sqlwork.com)|LINK
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.
Contributor
2770 Points
793 Posts
Re: How to trigger and run a javascript method when the HttpPost got JsonResult as response
Jul 30, 2020 05:38 AM|YihuiSun|LINK
Hi bsurendiran,
View
Controller
Here is the result.
Best regards,
Yihui Sun
Member
4 Points
95 Posts
Re: How to trigger and run a javascript method when the HttpPost got JsonResult as response
Jul 30, 2020 08:29 AM|bsurendiran|LINK
Thank you