7

我习惯了 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#。

4

3 回答 3

11

您需要在视图本身中放置断点。您可以使用 razor 语法在任何东西上放置断点,例如:

@Html.ActionLink
@{ var x = model.x; }

如果您遇到空引用异常,请在视图中使用模型的位置放置断点。

于 2013-06-24T17:50:22.243 回答
4

It would help to see the exception you are seeing. I'm guessing that you are seeing an exception when the page renders. As "David L" identified above, you want to set your breakpoint in the Razor view (Index.cshtml).

But why?

It helps to understand the lifecycle of a request/response in MVC. Here is the first example I found with a visual. There are sure to be others.

  • Request is routed to your Controller
  • The Controller returns a ActionResult: return View(cnty);
  • MVC passes the ActionResult to your View
  • The exception occurs in your Index.cshtml when attempting to use the ActionResult.

I'm going to speculate that it has something to do with a disposed DB context object. Depending on the ORM you are using, the result of

from r in db.Clients
where r.ClientID == id
select r

is an IQueryable<Client>. You may be surprised to find out that your code has not yet contacted the database before return View(cnty); is executed. Try this instead:

return View(cnty.ToList());

Again, the exact error you are seeing is important. My suggestion presumes Index.cshtml begins with:

@model IEnumerable<Client>

Update:

Per OP's comment below, the stack trace is not available. There are many questions dedicated to seeing the stack trace in your browser during development. At least confirm that the following is set in your web.config

<system.web>
    <customErrors mode ="Off" />
</system.web>
于 2013-06-24T18:11:33.787 回答
0

首先,使用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
            }
        }
于 2013-06-24T17:54:24.163 回答