简体   繁体   English

如何通过部分视图从ajax成功获取模型的特定数据

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

I want to get model's specific value in ajax success. 我想获得模型在Ajax成功中的特定价值。 I can not use Json result in here because I also need to load the model value in div container with partial view. 我不能在这里使用Json结果,因为我还需要使用部分视图将模型值加载到div容器中。

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. 我只想在ajax成功中获取IsCostUpdated的值。 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电话代码

$.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)
        }
    });

You can return a JsonResult in your current ActionResult . 可以在当前的ActionResult返回JsonResult Just check if the request being made is an ajax request. 只需检查发出的请求是否为ajax请求即可。 Your ActionResult would become something like this: 您的ActionResult将变成这样:

[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 您可以返回视图和json所需的数据,如下所示

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. 在该AJAX成功回调中,您可以访问数据对象,即在回调中称为“ d”的对象。

Try to console.log(d) and you will see that the d object has a responseJSON property. 尝试console.log(d) ,您将看到d对象具有responseJSON属性。 That is what you need to access your property. 那就是您访问您的财产所需要的。

Instead of doing: var isSuccess = d.IsCostUpdated; [I want this value] 而不是这样做: var isSuccess = d.IsCostUpdated; [I want this value] var isSuccess = d.IsCostUpdated; [I want this value] try var isSuccess = d.responseJSON.IsCostUpdated; var isSuccess = d.IsCostUpdated; [I want this value]试试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. 另一个重要的事情是,如果要将数据从控制器传递给ajax调用,请尝试执行以下操作: return Ok(model)而不是返回局部视图。 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. 如果返回部分视图,则该页面的html将作为响应数据传递到Ajax Success回调中的数据对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM