MVC ViewBag Best Practice

前端 未结 10 1857
野趣味
野趣味 2020-11-29 01:42

For the ViewBag, I heard it was a no-no to use. I would assume have the content from the ViewBag should be incorporated into a view model?

Question:

  1. <
相关标签:
10条回答
  • 2020-11-29 02:16

    If you cannot re-design EXISTING ViewModel use ViewBag.

    0 讨论(0)
  • 2020-11-29 02:16

    I thought I'd give my opinion on this, as I've used the ViewBag extensively.

    The only real benefits you'll get from using it are for a small project, or in cases where you have a new project and just want to get the ball rolling and not have to worry about creating loads of model classes.

    When your project is more mature, you may find issues with unexpected behaviour caused by using weak typing all over your application. The logic can be confusing, difficult to test and difficult to troubleshoot when things go wrong.

    I actually went down the route of completely removing the ViewBag from my applications, and preventing other developers from using it within the same codebase by throwing compilation errors when they try to, even within Razor views.

    Here's a sample ASP.NET 5 project on GitHub where I've removed it: https://github.com/davidomid/Mvc5NoViewBag

    And here's a blog post where I explain the motivations for removing it and an explanation on how the solution works: https://www.davidomid.com/hate-the-aspnet-mvc-viewbag-as-much-as-i-do-heres-how-to-remove-it

    0 讨论(0)
  • 2020-11-29 02:20

    2.Are there situations where a ViewBag is absolutely necessary?

    In some case you'll need to share your data from the Controller across the layouts, views and partial views. In this case, ViewBag is very helpful and I doubt there's any better way.

    0 讨论(0)
  • 2020-11-29 02:21

    If there were no use cases for it, it wouldn't be implemented in the first place. Yes you can do everything with ViewModels, but what if you don't really need one? One such scenario is editing entities. You can pass DTO directly as a model.

    @model CategoryDto
    <div class="md-form form-sm">
        <input asp-for="Name" class="form-control">
        <label asp-for="Name">("Category Name")</label>
    </div>
    

    But what if you want to select Category parent? Entity DTO ideally holds only it's own values, so to populate select list you use ViewBag

    <select asp-for="ParentId" asp-items="ViewBag.ParentList">
        <option value="">None</option>
    </select>
    

    Why do this? Well if you have 50 types of entities each with some sort of select from different values, you just avoided creating 50 extra ViewModels.

    0 讨论(0)
提交回复
热议问题