ASP.NET MVC, strongly typed views, partial view parameters glitch

后端 未结 4 866
花落未央
花落未央 2020-12-05 23:48

If i got view which inherits from:

System.Web.Mvc.ViewPage

Where Foo has a property Bar with a type string
And view wants

4条回答
  •  不思量自难忘°
    2020-12-06 00:20

    Though this has been answered, I ran across this and decided I wanted to solve this issue for my project instead of working around it with 'new ViewDataDictionary()'.

    I created a set of extension methods: https://github.com/q42jaap/PartialMagic.Mvc/blob/master/PartialMagic.Mvc/PartialExtensions.cs
    I also added some methods that don't call the partial if the model is null, this will save a lot of if statements.

    I created them for Razor, but a couple of them should also work with aspx style views (the ones that use HelperResult probably aren't compatible).

    The extension methods look like this:

    @* calls the partial with Model = null *@
    @Html.PartialOrNull("PartialName", null)
    @* does not call the partial if the model is null *@
    @Html.PartialOrDiscard("PartialName", null)
    

    There are also methods for IEnumerable models and the discard ones can also be called with a Razor lambda that allow you to wrap the partial result with some html.

    Feel free to use them if you like.

提交回复
热议问题