将ViewModel对象作为Json对象传递以进行查看

时间:2015-11-18 09:23:14

标签: jquery json asp.net-mvc-5

我试图将ViewModel对象作为Json对象传递给视图。

InquiryOrderViewModel

public class InquiryOrderViewModel
{
    public InquiryOrder InquiryOrder { get; set; }        
}

InquiryOrder型号

public class InquiryOrder
{
    [Key]
    public int InquiryOrderId { get; set; }

    public string InquiryOrderName { get; set; }

    [ForeignKey("ProductType")]
    public int ProductTypeId { get; set; }
    public virtual ProductType ProductType { get; set; }
}

InquiryOrderIndex视图和检索Json对象的脚本

@model eKnittingData.InquiryOrderViewModel

@using (Ajax.BeginForm("Save", "InquiryOrder", new AjaxOptions { UpdateTargetId = "IoResult", OnSuccess = "ajaxSuccess" }))
{
    @Html.TextBoxFor(a => a.InquiryOrder.InquiryOrderName)
    @Html.DropDownListFor(a => a.InquiryOrder.ProductTypeId, (SelectList)ViewBag.ProductTList, "Select")

    <input type="submit" value="Save" name="saveProp" class="btn btn-success" />
}

<script>
        $(document).on('click', '.myUpdateLink', function (e) {
            e.preventDefault();
            var inqOrdId = $(this).data('id');
            $.ajax({
                url: '@Url.Action("getForUpdate", "InquiryOrder")',
                type: "GET",
                dataType: "JSON",
                data: { InquiryOrderId: inqOrdId },
                success: function (io) {
                    alert("Successfully came from controller");
                    //How should i access elements in 'io'
                }
            }); 
        });
        </script>
控制器中的

JsonResult

public JsonResult getForUpdate(int InquiryOrderId)
    {
        var objContext = new KnittingdbContext();

        var inquiryOrderViewModel = new InquiryOrderViewModel();
        var inquiryOrderObj = (InquiryOrder)objContext.InquiryOrders.Where(a => a.InquiryOrderId == InquiryOrderId).FirstOrDefault();
        inquiryOrderViewModel.InquiryOrder = inquiryOrderObj;

        return Json(new { io = inquiryOrderViewModel }, JsonRequestBehavior.AllowGet);
    }

alert("Successfully came from controller")成功解雇。但我无法访问InquiryOrderViewModel的属性(例如:InquiryOrder,然后是InquiryOrder的属性)。我想要的是,访问该属性的值并使用InquiryOrderIndex视图(InquiryOrderNameProductTypeId)绑定它们。所有帮助赞赏。谢谢!

1 个答案:

答案 0 :(得分:1)

您传回一个名为io的属性命名的匿名对象,其中包含您的视图模型,因此要在ajax成功回调中访问它,它将是

success: function (io) {
    var name = io.io.InquiryOrder.InquiryOrderName;

但是您不应该将视图模型传递回客户端,除非该视图模型仅包含视图中所需的那些属性(并且从您的注释中包含其他属性,包括数据模型)。 Json()方法会对您的模型进行序列化,以便您通过网络发回的数据远远超过您所需的数据,从而降低性能。相反,发回你需要的东西

var order = (InquiryOrder)objContext.InquiryOrders.Where(a => a.InquiryOrderId == InquiryOrderId).FirstOrDefault();
var data = new { name = order.InquiryOrderName, product = order.ProductTypeId };
return Json(data, JsonRequestBehavior.AllowGet);

然后在视图中,设置文本框和下拉列表的值

success: function (data) {
    $('#InquiryOrder_InquiryOrderName').val(data.name);
    $('#InquiryOrder_ProductTypeId').val(data.product);
}