Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time errors for incorrect model in ASP.Net MVC

Is there any way where one can have compile time errors for strongly typed views. Let's say I have a view in the folder /Views/Home/Index.cshtml with the following code & strongly typed Model:

@model CSTemplate.Models.Home.HomeIndexModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

and then the controller, located at /Controllers/HomeController.cs would return the following code.

public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<string> s = new List<string>();
            return View(s);
        }

    }

As you can see, since the View() accepts an object as a model, the compiler won't complain that the model is invalid and would output a run-time error instead, which is:

Server Error in '/' Application.

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.String]', but this dictionary requires a model item of type 'CSTemplate.Models.Home.HomeIndexModel'.

Is there any way where I can get compile time errors instead of run time errors in case of such model type mismatch, or is there any workaround for this?

like image 737
Mark Cassar Avatar asked Sep 01 '25 11:09

Mark Cassar


1 Answers

From our discussions within this question it seems that there is no suggested workaround for such a scenario. Since the View takes as a parameter the model of type object, then the compiler will not complain if you by mistake pass in a model with a different type than that of the strictly typed model of the View. Pity since if you need to change the type of the strictly typed model of a View, the compiler will not inform you of such previous inconsistent models being passed over to the view but such errors are only notified during runtime.

like image 135
Mark Cassar Avatar answered Sep 02 '25 23:09

Mark Cassar