How to get model's specific data from ajax success with partial view

Viewed 2148

I want to get model's specific value in ajax success. I can not use Json result in here because I also need to load the model value in div container with partial view.

Here is my model

public class ProductModel
{
    public int ProductId { get; set; }

    public decimal? Cost { get; set; }

    public string Description { get; set; }

    public bool IsCostUpdated { get; set; }
}

I want to get the value of IsCostUpdated in ajax success only. In controller I have to returned strongly typed partial view. Here is the code

[HttpPost]
public ActionResult CheckProductCost(ProductModel model)
    {
        ModelState.Clear();
        using (var db = DataContext.Db)
        {
            model.IsCostUpdated = model.CheckUpdate(db);
        }

        return PartialView("ProductDataTable", model);
    }

this is my ajax call code

$.ajax({
        url: productCostUrl,
        dataType: 'html',
        type: 'POST',
        data: $('body').find('.productTable').closest('.dataComponent').find(':input').serialize(),
        success: function (d) {
            var isSuccess = d.IsCostUpdated; [I want this value]

           $('body').find('.productTable').html(d)
        }
    });
3 Answers

You can return a JsonResult in your current ActionResult. Just check if the request being made is an ajax request. Your ActionResult would become something like this:

[HttpPost]
public ActionResult CheckProductCost(ProductModel model)
{
    ModelState.Clear();
    using (var db = DataContext.Db)
    {
        model.IsCostUpdated = model.CheckUpdate(db);
    }

    if (Request.IsAjaxRequest()) // THIS IS AVAILABLE INSIDE THE SYSTEM.WEB.MVC ASSEMBLY
        return Json(new { IsCostUpdated = model.IsCostUpdated });

    return PartialView("ProductDataTable", model);
}

you can return both the view and the data needed with json like below

return Json(new
                    {
                        view = RenderRazorViewToString(ControllerContext, "ProductDataTable", model),
                        IsCostUpdated = model.IsCostUpdated
                    });


// Render Razor view as string to populate dom
public static string RenderRazorViewToString(ControllerContext controllerContext, string viewName, object model)
        {
            controllerContext.Controller.ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var ViewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
                var ViewContext = new ViewContext(controllerContext, ViewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, sw);
                ViewResult.View.Render(ViewContext, sw);
                ViewResult.ViewEngine.ReleaseView(controllerContext, ViewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }

// Razor View - Ajax call Success
success: function (data) {
                    $('body').find('.productTable').html(data.view);
                    var isSuccess = data.IsCostUpdated;
                }

Inside that AJAX Success callback you have acces to the data object, the one that you call "d" in your callback.

Try to console.log(d) and you will see that the d object has a responseJSON property. That is what you need to access your property.

Instead of doing: var isSuccess = d.IsCostUpdated; [I want this value] try var isSuccess = d.responseJSON.IsCostUpdated;

Another important thing, if you want to pass data from your controller to your ajax call, try to do: return Ok(model) instead of returning a partial view. If you return a partial view, the html of that page will be passed as response data to your data object in Ajax Success callback.

Related