我是MVC的新手,制作了一个适用于我本地计算机的应用程序(带有SQLExpress的Windows 7)但是当我在Windows 2008 R2,SQL 2008 R2和IIS7上进行实时部署时,我收到此错误:“抱歉,出错在处理您的请求时发生了“
以下是相关代码的摘要:
WEB.CONFIG connectionStrings
add name="RentalEntities" connectionString="Data Source=[ServerName];Initial Catalog=[DatabaseName];Integrated Security=True" providerName="System.Data.SqlClient"
的HomeController
namespace Rental.Controllers
{
RentalEntities rentalDB = new RentalEntities();
...
public ActionResult Index()
{
var listings = from l in rentalDB.Listings select l;
return View(listings.ToList());
}
}
HOME / INDEX.CSHTML
@model List<Rental.Models.Listing>
@foreach (var listing in Model)
{
@listing.ListingName <br />
}
此行@foreach (var listing in Model)
发生错误,与null有关 - 请注意,数据库中的NONE字段为null。任何帮助将不胜感激。
以下是完整的错误消息:[第13行是:foreach (var listing in Model)
Sorry, an error occurred while processing your request.
System.NullReferenceException: Object reference not set to an instance of an object. at ASP._Page_Views_Home_Index_cshtml.Execute() in c:\inetpub\wwwroot\projects\Rentals\Views\Home\Index.cshtml:line 13 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.StartPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
答案 0 :(得分:0)
这里发生的事情是您已将空值传递给index.cshtml
的模型。
代码是null
的预告。
在Prod中调试:
尝试在INDEX.CSHTML上设置一些调试信息
@(Model==null) //will write to page whether the model data being passed is null.
在Dev / Test中调试:
Index()
的行中为自己设置断点。将其设置为return View(listings.ToList());
。它实际上是空的吗?然后在视图中为null检查设置断点。在foreach
之前,运行检查null:
@if (Model != null)
{
foreach (var foo in Model)
{
//your code
}
}
else
{
@: Model Is null!
}