gpt4 book ai didi

jquery - 将 ViewModel 对象作为 Json 对象传递给 View

转载 作者:行者123 更新时间:2023-12-01 01:32:31 25 4
gpt4 key购买 nike

我尝试将 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 View 和检索 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>
Controller 中的

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("成功来自 Controller ") 成功触发。但我无法访问它的 InquiryOrderViewModel 属性(例如:InquiryOrder 然后是 InquiryOrder 的属性)。我想要的是,访问该属性的值并将其与 InquiryOrderIndex view(InquiryOrderName,ProductTypeId) 绑定(bind)。感谢所有帮助。谢谢!

最佳答案

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

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

但是您不应该将 View 模型传递回客户端,除非该 View 模型仅包含 View 中所需的属性(并且从您的注释中包含其他属性,包括数据模型)。 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);

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

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

关于jquery - 将 ViewModel 对象作为 Json 对象传递给 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33776058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com