質問

I'm learning on Visual Studio on C# with MVC.

I've made a link on the Index page with <a class="btn">

How can I throw an exception from pushing it? Well it shouldn't throw always an exception, maybe in 1 of a 5 times.

But I'm just wondering for now how to link the exception to the link.

役に立ちましたか?

解決

I assume you mean you're using ASP.NET MVC.

To do this, you'd need to create a link to points to an action in your controller. This can be an existing action to test or a new action.

When you click the link, the browser will send a GET request to your application which will route to your controller to the appropriate action to handle the request. Here you can choose whatever method you like to determine whether you want to throw an exception (for instance using a random number, counting the requests in a static variable, etc.)

When you throw an exception, ASP.NET MVC will likely route you to the Error view (in your Views/Shared/Error.cshtml) with the exception information passed to the View which, by default, doesn't render any specific information about it.

If you decide not to throw a new exception, you can just return the appropriate view. If you've started with a standard ASP.NET MVC project, there will be some basic code already in place which demonstrates this behavior.

EDIT to address your comment:

If you create an action in your home controller like this:

public ActionResult ExceptionLink()
{
    Random r = new Random();
    if (r.Next(5) == 1)
        throw new Exception("Exception is thrown somewhat randomly");

    return RedirectToAction("Index");
}

Then in your view you can use the HTML helper to generate the link:

@Html.ActionLink("Link to click", "ExceptionLink", "Home", new { @class="btn"})

When the link is clicked, the ExceptionLink method will be invoked. It might throw an exception or it might redirect the user back to the index page. Alter logic as needed.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top