View text population using ViewBag - asp.net-mvc

I have a partial view with some text that can be modified using the ViewBag
#(ViewBag.FooText ?? "foo")
I populate ViewBag.FooText in the parent view from a resource file:
#
{
ViewBag.FooText = MyResources.Common.FooText
}
My question is whether this is the best place to populate this property (and all other text resources) or would the related controller, or somewhere else, be more appropriate?

I would suggest not using ViewBag if you can help it. It is better to use a strongly-typed viewmodel object, bind the resources to that object (in the controller or in the object itself), and then push the viewmodel to the partial view.

ViewBag isn't the best place to "populate" any property or data.
It will be much better if you store it in the Model. Model View Controller...
Read this answer of #Darin Dimitrov, an MVC master over here...

Related

Should I always use a view model or is it ok to use ViewData?

when do you think is it better to use ViewData over a view model?
I have the same exact partial view in a couple of main views. I'd like to control how a partial view is rendered but I'd also prefer the partial view to accept only a view model which is a collection of records, just a pure IEnumerable<> object. I'd rather avoid to send the full view model object from a main view because it also contains a lot of different properties, objects, that control paging, sorting, filtering etc.
Therefore the question is if I should create another view model for the partial view or is it ok to use ViewData? I've read soemwhere that using ViewData is a very bad practice.
With View Data, I could simply pass require details like this:
#{
ViewDataDictionary vd = new ViewDataDictionary
{
new KeyValuePair<string,object>("WithDelete", Model.WithDelete),
new KeyValuePair<string,object>("WithRadarCode", Model.WithCode)
};
}
// ...
#if (Model != null) {
Html.RenderPartial("_ListOfRecordingsToRender", Model.recordingViewModel, vd);
}
At the moment, it would be sorted out.
My worry is that currently this *.recordingViewModel has plenty of different variations in my project, because of different models for creating / editting, listing, shoing details of a record etc. I feel like it may start to be too messy in my project if I make view model for each action.
What do you think. Please could you advice on that particular problem. Thanks
I think you should stick to using a ViewModel, your ViewModel is the class that defines your requirements for the view.
My reason behind this is that in the long run, it will be a lot more maintainable. When using ViewBag it's a dynamic class so in your views you should be checking if the ViewBag property exists (And can lead to silly mistakes like typo's) e.g.:
if(ViewBag.PropertyName != null)
{
// ViewBag.PropertyName is a different property to ViewBag.propertyName
}
This type of code can make your View's quite messy. If you use a strongly typed model, you should be able to put most of the logic in your controllers and keep the View as clean as possible which is a massive plus in my books.
You also will also end up (if you use ViewBag) attempting to maintain it at some point and struggle. You are removing one great thing about C#, it's a strongly typed language! ViewBag is not strongly typed, you may think you are passing in a List<T> but you could just be passing a string.
One last point, you also will lose out on any intellisense features in Visual Studio.
I feel like it may start to be too messy in my project if I make view model for each action.
Wont it just be as messy in your controllers assigning everything to a ViewBag? If it was a ViewModel you could send it off to a 'Mapping' class to map your DTO to your View.
Instead of this:
// ViewModel
var model = new CustomViewModel()
{
PropertyOne = result.FirstResult,
PropertyTwo = result.SecondResult,
}
//ViewBag
ViewBag.PropertyOne = result.FirstResult;
ViewBag.PropertyTwo = result.SecondResult;
You could do this:
var mapper = new Map();
var model = mapper.MapToViewModel(result);
*You would obviously need to provide an implimentation to the mapping class, look at something like Automapper
I'd also prefer the partial view to accept only a view model which is a collection of records, just a pure IEnumerable<> object. I'd rather avoid to send the full view model object from a main view because it also contains a lot of different properties, objects, that control paging, sorting, filtering etc.
That is fine, just create a view model that has a property of IEnumerable<T>. In my opinion you should try and use a strongly typed ViewModel in all of your scenarios.

MVC model casting in partial view, f__AnonymousType6

Is it possible to cast a model going into a partial view?
#Html.Partial(Model.Partial, new { model =
((WarningPopupModel)CommonData.NotificationPopup.PopupModel) })
Here PopupModel is of type object but holds an instance of WarningPopupModel, when I try this is the error I get
Additional information: The model item passed into the dictionary is of type
'<>f__AnonymousType6`1[EmployeeKiosk.Models.WarningPopupModel]',
but this dictionary requires a model item of type
'EmployeeKiosk.Models.WarningPopupModel'.
So really I need to understand the 'f__AnonymousType6' part and know what kind of flexibility I have here
Background.
I want to create a popup in the view depending on some business logic, so ultimately the controller will pass back the name of the view (or it could be a token) together with some model.
In the view I just need some way of being able to switch between the partial views that appear, the partial views will be Kendo popups
thanks
Pretty sure that you should just be able to change it to;
#Html.Partial(Model.Partial, (WarningPopupModel)CommonData.NotificationPopup.PopupModel);
Without the new { model = ... } part.

MVC.ViewBag is wrong?

I'm using
ViewBag.Something = session.Query<Something>().ToList();
To pass information from class Something to View and use it in selectList
#Html.DropDownListFor(model => model.model, new
SelectList(ViewBag.Something, "Id", "name"), "--Smthing--")
Is that bad? and how can i change it to be better?
The practice is not at all bad but it is recommonded to have a List property in our mode it self. in your case something like
public ActinResult YourActionMethod()
{
YourModelObject.Something = session.Query<Something>().ToList();
// And return your view after further code statements
return View(YourModelObject);
}
Infact instead of the original list object you cancreate a SelectList object where you can easily bind key and value and send it to view. By this way you can add all your business and build your model at once place and can populate it from the location you want to. Later View will just use that model rather than applying some more intelligence to it. It helps alot as all your values resides under same object rather than some in Model and some in ViewBag.
Secondly this practice is also fine if you don't have this list at more than one place and you are not reusing this model in any views. Also if you want to access this property outside your view e.g. in Layout or in some parent view which is consuming your view.
You can take a look at following post which explains how to bind a list to your model.
Setting default selected value of selectlist inside an editor template
I prefer to add all my properties to the model of the view, but the ViewBag can be useful to add things that don't quite fit in the model. It can also be useful when binding to elements in the layout since it doesn't have access to the view's model.

MVC3 ASPX ViewBag / Model

I have a view that is using a model
Inherits="System.Web.Mvc.ViewPage<Program.Models.Test>"
I am displaying data in the view using:
> <%= this.Model.Item == null ? "" :
> Html.GetString(this.Model.Item.Name) %>
Now I am trying to display a different item from another model on the same view, I thought ViewBag might help, so in my controler, I added:
ViewBag.GuideLines = ctx.GuideLines;
My question is can I display a specific item value from Guidelines model on the same view?
Thanks in advance.
I thought ViewBag might help
Wrong thought. ViewBag/ViewData never helps. I never use those 2 in any ASP.NET MVC application.
Now I am trying to display a different item from another model on the same view
Simply add this other model as property of the main view model. So you will have Model.Guidelines in the view.
in general if you need to use one or more of your domain models for use in a single page, you would create a viewmodel, basically a POCO that would contain just the properties from your domain objects (or any other information) that your view would need to be aware of. you would then strongly ype your view to this new viewmodel type and access the properties as per normal.

Pass data to User Control ASP.NET MVC

I have a user control which shows list of latest announcements. This user control would be used in almost 90% of my pages. Now my concern is how to pass data to this user control for latest announcements.
My first approach is to make a base controller and in Initialise method I pass data to user control via ViewBag/ViewData. All my other controllers derive from this base controller. This looks nice but my concern is that it may become an overkill for some simple solution existing already out there. Also I would need to make sure that no controller ever fiddles with my Viewdata/Viewbag data meant for my usercontrol.
Please let me know if this is correct way of proceeding ahead or there exists some better solution.
Thanks
Assuming you have a "user control" (you should try to refer to them as partial view's in MVC) that looks like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Announcement>>" %>
This means your partial view expects a list of Announcement objects.
Now, the question is - where are you rendering this partial view?
You could be doing it from a master page, you could be doing it from a view, or you could be doing it from another partial view.
Either way, the code to render the partial needs to look like this:
<% Html.RenderPartial("LatestAnnouncements", announcements) %>
But - where do you get the announcements from.
Assuming you have a Repository/DAL/helper method to get the latest announcements - i think you should have the ViewModel's you require inheriting from a base ViewModel:
public class AnnouncementViewModelBase
{
protected IEnumerable<Announcement> GetAnnouncements()
{
// call DAL
}
}
Then any master/view/partial that needs to render the latest announcements partial should be bound to a ViewModel which inherits from that base view model.
In the cases where the master/view/partial is not strongly-typed (e.g dynamic view), you can stick it in the ViewData. But if you have organized your view's correctly this shouldn't be required.
Is this the kind of thing you're after? How to pass data from view to UserControl in ASP.NET MVC?
You should use RenderAction in this kind of scenario, so that you do not have bother to pass the required data in each action method of your controllers.
I think the best way would be to use #Html.Action. This would allow me to call my actions dedicated to my usercontrols data and I can call it from anywhere.

Resources