我试图将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
视图(InquiryOrderName
,ProductTypeId
)绑定它们。所有帮助赞赏。谢谢!
答案 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);
}