Getting a null exception as model in razor

2019-09-06 17:29发布

问题:

I have an error's view in my asp.net mvc4 application like this:

@model System.Web.Mvc.HandleErrorInfo

@{
    ViewBag.Title = "Erreur";
}
<p>Take it easy</p>
<hgroup class="title">
    <h1 class="error">Erreur = @Model.Exception</h1>
    <h1 class="error">Controller = @Model.ControllerName</h1>
    <h1 class="error">Name = @Model.ActionName</h1>
    <h2 class="error">Une erreur s'est produite lors du traitement de la requête.</h2>    
</hgroup>

The controller code :

 public class HomeController : Controller
 {
     [HttpGet]
     public ActionResult Index()
     {
         return RedirectToAction("Search");
     }

     public ActionResult Error()
     {
         return View();
     }

     public ActionResult About()
     {
         ViewBag.Message = "Votre page de description d’application.";

         return View();
     }

     public ActionResult Contact()
     {
         ViewBag.Message = "Votre page de contact.";

         return View();
     }

The problem is that the Model is always null. What is the reason for this?

回答1:

You're not even providing the error object to the view.

    public ActionResult Error()
    {



        return View();
    }


回答2:

You can pass a instance of your model object to the View() method, by instance

public ActionResult Error()
{
    ErrorViewModel vm=new ErrorViewModel();
    vm.prop1="This is the error message";

    return View(vm);
}


回答3:

Actually this is a good question. You do not really need to pass the model in question to the view. What you do need to do is make sure that the appropriate filter is set. In MVC 4, you can do this in global.asax.cs:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
       filters.Add(new HandleErrorAttribute());
    }

Make sure this gets called in application_start:

    protected void Application_Start()
    {       
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        ModelBinders.Binders.DefaultBinder = new DevExpress.Web.Mvc.DevExpressEditorsBinder();
    }

Now your HandleErrorInfo model will be populated and passed to your error view automatically.