简体   繁体   中英

Getting a null exception as model in razor

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?

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);
}

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

    public ActionResult Error()
    {



        return View();
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM