![](/img/trans.png)
[英]How can i create a Partial View for MVC4 or MVC 5 using Entity Framework (.edmx Model) with Razor Views?
[英]How can I debug mvc4 razor views?
我已經習慣了C#和vb.net winforms,通常可以通過設置斷點並單步執行代碼來找到我需要的所有錯誤。
我想知道我做錯了什么。
我在這里放置一個斷點:
public ActionResult Index(int id)
{
var cnty = from r in db.Clients
where r.ClientID == id
select r;
if (cnty != null) // breakpoint here
{
return View(cnty); // F11 jumps over this section of code returning me to the error page below.
}
return HttpNotFound();
}
然而,我再也不知道它究竟在哪里或為什么會出錯。 我怎樣才能找出原因或更好的錯誤呢?
我正在使用VS2012 mvc4 c#。
您需要在視圖中放置斷點。 您可以使用razor語法在任何地方放置斷點,例如:
@Html.ActionLink
@{ var x = model.x; }
如果您獲得空引用異常,請在視圖中使用模型的位置放置斷點。
看到你看到的異常會有所幫助。 我猜你在頁面呈現時看到了異常。 正如上面標識的“David L”,您希望在Razor視圖( Index.cshtml
)中設置斷點。
但為什么?
它有助於理解MVC中請求/響應的生命周期。 這是我用視覺發現的第一個例子 。 肯定會有其他人。
ActionResult
: return View(cnty);
ActionResult
傳遞給您的View ActionResult
時, Index.cshtml
會發生異常。 我將推測它與已處置的DB上下文對象有關。 根據您使用的ORM,結果
from r in db.Clients
where r.ClientID == id
select r
是一個IQueryable<Client>
。 在return View(cnty);
之前,您可能會驚訝地發現您的代碼尚未聯系數據庫return View(cnty);
被執行。 試試這個:
return View(cnty.ToList());
同樣,您看到的確切錯誤很重要。 我的建議假定Index.cshtml
以:
@model IEnumerable<Client>
更新:
根據下面的OP評論,堆棧跟蹤不可用。 有許多問題專門用於在開發過程中查看瀏覽器中的堆棧跟蹤。 至少確認在web.config
設置了以下內容
<system.web>
<customErrors mode ="Off" />
</system.web>
首先,使用try
塊。 您的例外情況將在catch區塊中提供,以供檢查,報告等。
public ActionResult Index(int id)
{
try
{
var cnty = from r in db.Clients
where r.ClientID == id
select r;
if (cnty != null) // breakpoint here
{
return View(cnty); // F11 jumps over this section of code returning me to the error page below.
}
return HttpNotFound();
}
catch (Exception ex)
{
//report error
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.