我有一个工作的创建页面,它使用JavasScript来拉动各种数据字符串,并在前端显示它们。MVC 4编辑控制器抛出NullReferenceException当使用.getJSON调用
当我试图在同一视图的编辑页面中实现类似的代码时,我遇到了一个“NullReferenceException” - 对象引用未设置为对象的实例。
下面是在“ProductController的”编辑方法,错误是在IF语句抛出:
public ActionResult Edit(int id = 0)
{
using (ManagePromotion promLogic = new ManagePromotion(ref uow))
using (ManageDistributionRule druleLogic = new ManageDistributionRule(ref uow))
{
Product prd = ProductLogic.GetByAndInclude(x => x.ProductID == id, new List<string>() { "AddSamplePacks" }).FirstOrDefault();
ProductVM vm = new ProductVM(prd, (int)System.Web.HttpContext.Current.Session["CustomerID"]);
if (vm.Product.AddSamplePacks == null || promLogic.GetById(vm.Product.PromotionID).CustomerID != (int)System.Web.HttpContext.Current.Session["CustomerID"])
{
throw new HttpException(404, "");
}
return View(vm);
}
}
下面也就是我一直在添加到编辑页面前端的JavaScript,如果我删除此代码的页面运行正常,没有错误:
var input = "comm";
//
//alert("HIT");
$.getJSON('getCat', { term: input }, function (result) {
var ddl = $('#selectTypeCat');
alert(result);
//
var length = result.length;
ddl.empty();
$(document.createElement('option'))
.attr('value', 0)
.text("-- Please Select --")
.appendTo(ddl);
$(document.createElement('option'))
.attr('value', 100)
.text("All Distribution Rules")
.appendTo(ddl);
$(result).each(function (jack) {
//
$(document.createElement('option'))
.attr('value', result[jack])
.text(result[jack])
.appendTo(ddl);
});
});
在产品控制器,它与创建过程中工作得很好,在“getCat”的方法是这样的:
public ActionResult getCat(string term)
{
int customerId = (int)System.Web.HttpContext.Current.Session["CustomerID"];
//
//string term = "small";
//
var getCat = (from ctype in TypeLogic.GetCustomerProdIndex(customerId, term).List
select new { ctype.TypeName, ctype.TypeCategoryID }).ToList();
List<String> returnList = new List<string>();
foreach (var item in getCat)
{
returnList.Add(item.TypeName.ToString());
}
returnList = returnList.Distinct().ToList();
return Json(returnList, JsonRequestBehavior.AllowGet);
}
任何帮助将不胜感激,谢谢。
请出示“getCat”功能是不是在更新控制器 –
,感谢 – Cooper1810
的根本原因是您尝试在vm.Product.AddSamplePacks获得值,其中vm.Product为空(见我的回答) –