Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC6 Strongly typed action links and views

We are currently getting a new application stood up with MVC6. In previous versions, we used T4MVC so we could do stuff like:

@Url.Action(MVC.Home.Index);

and

return View(MVC.Home.Views.Index, model);

In the new application I have to use magic strings. I Hate magic strings. Are there any alternatives for this for MVC6?

like image 593
Chris Kooken Avatar asked Jan 06 '16 21:01

Chris Kooken


People also ask

What are strongly typed views?

Strongly typed views are used for rendering specific types of model objects, instead of using the general ViewData structure. By specifying the type of data, you get access to IntelliSense for the model class.

What is strongly typed view in MVC 5?

In ASP.NET MVC, we can pass the data from the controller action method to a view in many different ways like ViewBag, ViewData, TempData and strongly typed model object. If we pass the data to a View using ViewBag, TempData, or ViewData, then that view becomes a loosely typed view.

What are the advantages of using strongly typed views?

The ASP.NET Core provides the ability to pass strongly typed models or objects to a view. This approach helps us with the intellisense and better compile-time checking of our code. The scaffolding mechanism in Visual Studio can be used to create the View.


1 Answers

Came across this AspNet.Mvc.TypedRouting Repository on GitHub that I thought would be useful when I eventually move over to MVC6.

Not sure if it handles views as well though

Some instructions from the readme

To use expression based link generation, you need to do the following into your Startup class:

public void Configure(IApplicationBuilder app)
{
   // other configuration code

   app.UseMvc(routes =>
   {
        routes.UseTypedRouting();
   });
}

Basically, you can do the following:

// generating link without parameters - /Home/Index
urlHelper.Action<HomeController>(c => c.Index());

// generating link with parameters - /Home/Index/1
urlHelper.Action<HomeController>(c => c.Index(1));

// generating link with additional route values - /Home/Index/1?key=value
urlHelper.Action<HomeController>(c => c.Index(1), new { key = "value" });

// generating link where action needs parameters to be compiled, but you do not want to pass them - /Home/Index
// * With.No<TParameter>() is just expressive sugar, you can pass 'null' for reference types but it looks ugly
urlHelper.Action<HomeController>(c => c.Index(With.No<int>()));
like image 191
Nkosi Avatar answered Oct 05 '22 09:10

Nkosi