I have retrieved data from database using a LINQ query.
var data = (from z in db.BlogPostTbl
where z.PostId == id
select z).ToList();
in this result, I have an attribute name user_rankings. The value for this field is [1,2,3] in database but I have to display as good if 3, better if 2 or best if 1. How can I do this?
<td><b>User Ranking:</b> #Html.DisplayFor(modelItem => item.user_rankings) </td>
Example of using the Enum type.
Defining the UserRankingEnum type and the GetEnumDescription() method to obtain a description by the enum value:
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace WebApp.Models
{
public class BlogPost
{
public int PostId { get; set; }
public int user_rankings { get; set; }
}
public enum UserRankingEnum
{
[Description("BEST")]
Best = 1,
[Description("BETTER")]
Better = 2,
[Description("GOOD")]
Good = 3
}
public static class EnumExtension
{
public static string GetEnumDescription(this UserRankingEnum value)
{
if (value.GetType().GetField(value.ToString()) is FieldInfo fi)
{
if (fi.GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attributes && attributes.Any())
{
return attributes.First().Description;
}
}
return value.ToString();
}
}
}
The view accordingly:
#using WebApp.Models
#model IList<WebApp.Models.BlogPost>
#foreach (var item in Model)
{
<div>
<b>User Ranking: </b>
#{ var description = ((UserRankingEnum)item.user_rankings).GetEnumDescription(); #Html.DisplayFor(m => description) }
</div>
}
One possibility is to use a separate view model class / poco and map the db entity to this poco:
var data = (from z in db.BlogPostTbl
where z.PostId == id
select new BlogPostViewModel()
{
Ranking = GetRankingDescription(z.user_rankings)
}).ToList();
public class BlogPostViewModel
{
public string Ranking { get; set; }
}
private static string GetRankingDescription(int ranking)
{
switch (ranking)
{
case 1:
return "best";
case 2:
return"better";
case 3
return"good";
default
return "";
}
}
I think you want something like this
// inside the razor page
#foreach (var item in Model)
{
string rank_ = "";
switch(item.user_rankings)
{
case "1":
ward_ = "BEST";
break;
case "2":
ward_ = "BETTER";
break;
case "3":
ward_ = "GOOD";
break;
}
<td><b>User Ranking:</b> #rank_ </td>
}
I could have sworn that you can use the
public enum UserRankingEnum
{
[Description("BEST")]
Best = 1,
[Description("BETTER")]
Better = 2,
[Description("GOOD")]
Good = 3
}
and then
#Html.DisplayFor(modelItem => item.user_rankings)
Will display the description. In fact checked some code and it should do.
Although it depends on what you need and things like multi-lingual reasons might mean you lean towards a table or some other way to support it.
Related
I am wondering if there is some clever way to retrieve data from an enumerable using LINQ when individual values from multiple records are needed.
For example, let's say you have a person with three different phone fields:
public class Person
{
public Phone HomePhone { get; set; }
public Phone WorkPhone { get; set; }
public Phone CellPhone { get; set; }
}
...but the phone list is stored in a normalized format:
public enum PhoneType
{
Home, Work, Cell
}
public class Phone
{
public PhoneType Type { get; set; }
public string Number { get; set; }
}
static public IEnumerable<Phone> GetPhoneList()
{
yield return new Phone { Type = PhoneType.Home, Number = "8005551212" };
yield return new Phone { Type = PhoneType.Work, Number = "8005551313" };
yield return new Phone { Type = PhoneType.Cell, Number = "8005551414" };
}
If you needed to populate Person, you could write a loop, and get everything you need in one pass:
public static Person GetPerson1()
{
var result = new Person();
foreach (var ph in GetPhoneList())
{
switch (ph.Type)
{
case PhoneType.Home: result.HomePhone = ph; break;
case PhoneType.Work: result.WorkPhone = ph; break;
case PhoneType.Cell: result.CellPhone = ph; break;
}
}
return result;
}
But if you wanted to use LINQ, it seems like three passes may be needed:
public static Person GetPerson2()
{
return new Person
{
HomePhone = GetPhoneList().Single( ph => ph.Type == PhoneType.Home ),
WorkPhone = GetPhoneList().Single( ph => ph.Type == PhoneType.Work ),
CellPhone = GetPhoneList().Single( ph => ph.Type == PhoneType.Cell )
};
}
Is there a clever way to use LINQ to get it all with only one pass over the enumeration?
Here is a link to a Fiddle if you'd like to explore my code.
(I am aware I could use a dictionary or other data structure to solve this particular problem; this is just an example.)
Normally, you can't do this in LINQ.
If you really want to, you can create a Foreach extension method and do the same as your GetPerson1 method.
public static class Ext
{
public static void Foreach<T>(this IEnumerable<T> e, Action<T> action)
{
foreach (T item in e)
{
action(item);
}
}
}
and then
public static Person GetPerson2()
{
var p = new Person();
var pl = GetPhoneList();
pl.Foreach(ph =>
{
switch (ph.Type)
{
case PhoneType.Home: p.HomePhone = ph; break;
case PhoneType.Work: p.WorkPhone = ph; break;
case PhoneType.Cell: p.CellPhone = ph; break;
}
});
return p;
}
But you really shouldn't. LINQ is meant to operate on IEnumerables (item by item), and LINQ functions should be without side effects, while your foreach loop and Foreach extension methods are only creating side effects, changing the state of the Person object.
And, besides, the fact that you need a 'clever way' should be an indication that this is not the way it's meant to be used :)
There's a great article by Eric Lippert with more details here: https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/
If there is no guarantee that numbers from the same person come in a sequence then you have to enumerate the list until you find all the numbers. It does not seem to me this is a good candidate for LINQ, whose purpose is to make the code more readable. Your foreach is just fine, and I would just break the loop when all numbers are found.
If you want to enumerate all the persons, and not just one then Dictionary approach is probably most effective. GroupBy internally uses a dictionary and you can use GroupBy to collect all the numbers belonging to a person, and then Aggregate to make a Person out of them. Let's assume there is some property Phone.PersonID, and also Person.PersonID, then you would have something like this:
GetPhoneList()
.GroupBy(x => x.PersonID)
.Select(x => x.Aggregate(new Person() { PersonID = x.Key },
(person, phone) =>
{
switch (phone.Type)
{
case PhoneType.Home: person.HomePhone = phone; break;
case PhoneType.Work: person.WorkPhone = phone; break;
case PhoneType.Cell: person.CellPhone = phone; break;
}
return person;
}));
I assume here that GetPhoneList() returns all the phones of all persons.
Using ASP.NET MVC, .NET Framework 4.5.2, Entity Data Model for SQL DB, Visual Studio 2017.
I have a class generated from the ADO.NET(EF Designer from Database) :
BookInfo.cs
namespace LibraryMS
{
using System;
using System.Collections.Generic;
public partial class BookInfo
{
public string BookID { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public string PublishDate { get; set; }
public string Edition { get; set; }
public virtual Inventory Inventory { get; set; }
}
}
The database is designed where the "BookID" in the BookInfo table has a foreign key "BookID" in the Inventory table.
In a view to update an inventory's properties referenced by "BookID", I then proceed to query the list and update the correct instance.
Screenshot of update inventory page:
When landing on page to enter info the [HttpGet] UpdateInventory() is called, when clicking "Create" button as seen above, the [HttpPost] UpdateInventory(...) is called.
Logic/Code in Controller:
[HttpGet]
public ActionResult UpdateInventory()
{
return View();
}
[HttpPost]
public async Task<ActionResult> UpdateInventory(string bookID, string ttlIn, string lowin, string outnow)
{
var bf = await SqlRestApiHelper.searchFromBooks(bookID);
bf.Inventory.TotalIn = Convert.ToInt16(ttlIn);
bf.Inventory.LowIn = Convert.ToInt16(lowin);
bf.Inventory.Out = Convert.ToInt16(outnow);
await SqlRestApiHelper.UpdateBookInfoInventory(bf.Inventory);
await SqlRestApiHelper.SaveChanges();
return View("All");
}
[HttpGet]
public async Task<ActionResult> All()
{
return View(await SqlRestApiHelper.getAllBooksInfo(0, 10));
}
SqlRestApiHelper.cs
namespace LibraryMS
{
public static class SqlRestApiHelper
{
private static libraryDBEntities entities = new libraryDBEntities();
public static async Task<LibraryMS.BookInfo> searchFromBooks(string id)
{
return entities.BookInfoes.ToList().Find(book => book.BookID == id);
}
public static async Task UpdateBookInfoInventory(LibraryMS.Inventory inv)
{
var newInv = inv;
var el = entities.BookInfoes.ToList().Find(x => x.Inventory.BookID == newInv.BookID);
if (el != null)
{
el.Inventory.TotalIn = newInv.TotalIn;
el.Inventory.LowIn = newInv.LowIn;
el.Inventory.Out = newInv.Out;
// the above updates the list item referenced
}
}
public static async Task SaveChanges()
{
await entities.SaveChangesAsync();
}
public static async Task<IPagedList<BookInfo>> getAllBooksInfo(int page, int itemsPerPage)
{
List<BookInfo> bookinfo = new List<BookInfo>();
bookinfo = (from o in entities.BookInfoes
orderby o.Title descending //use orderby, otherwise Skip will throw an error
select o)
.Skip(itemsPerPage * page).Take(itemsPerPage)
.ToList();
int totalCount = bookinfo.Count();//return the number of pages
IPagedList<BookInfo> pagebooks = new StaticPagedList<BookInfo>(bookinfo, page + 1,10,totalCount);
return pagebooks;//the query is now already executed, it is a subset of all the orders.
}
The Null Exception Thrown:
Code for all.cshtml view page:
#model PagedList.IPagedList<LibraryMS.BookInfo>
#using PagedList.Mvc;
#{
ViewBag.Title = "All";
}
<h2>all</h2>
<table class="table">
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Publisher)
</td>
<td>
#Html.DisplayFor(modelItem => item.PublishDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Edition)
</td>
<td>
#Html.ActionLink("Details","Details",new { item.BookID})
</td>
</tr>
}
</table>
#Html.PagedListPager(Model, page => Url.Action("All","BookInfoController", new { page }))
your view is throwing error because you are returning the view without passing the model, you are using return View("All") without passing the model
the right way is by passing the model with the view, you can do it this way
View("ViewName", ModelData);
in your case
return View("All", await SqlRestApiHelper.getAllBooksInfo(0, 10));
for the saving part I am not sure why, but i can see few errors,
first what if book does not have inventory info ?
it will throw null error, so first check if null, create new inventory, if not update accordingly
here is how i would do it
public static async Task UpdateBookInfoInventory(Inventory inv)
{
var newInv = inv;
// get book info
var el = entities.BookInfoes.FirstOrDefault(x => x.BookID == inv.BookID);
if (el != null)
{
if(el.Inventory != null)
{
// update accordingly
el.Inventory.TotalIn = newInv.TotalIn;
el.Inventory.LowIn = newInv.LowIn;
el.Inventory.Out = newInv.Out;
// the above updates the list item referenced
}
else
{
/// add new if null
el.inventory = newInv;
}
await SqlRestApiHelper.SaveChanges();
}
As a first step , put the breakpoint in the getAllBooksInfo method and see whether the list count is coming or not in visual studio. This will help you a lot.
And As an alternative step, you can also solve this error by using the ToPagedList(pageIndex, pageSize); method, i have used it personally and it was worked well
ToPagedList example as per your code:
**public static async Task<IPagedList<BookInfo>> getAllBooksInfo(int page, int itemsPerPage)
{
List<BookInfo> bookinfo = new List<BookInfo>();
bookinfo = (from o in entities.BookInfoes
orderby o.Title descending //use orderby, otherwise Skip will throw an error
select o)
.Skip(itemsPerPage * page).Take(itemsPerPage)
.ToList();
int totalCount = bookinfo.Count();//return the number of pages
//changes made to the below line
IPagedList<BookInfo> pagebooks = bookinfo.ToPagedList(1, 10);
return pagebooks;//the query is now already executed, it is a subset of all the orders.
}**
official source:https://github.com/troygoode/PagedList
Note: Even with this approach, kindly check whether you are getting the data or not from the database by using the breakpoint in the changed line.
Hope this will surely solve your problem kindly let me know thoughts or feedbacks
Thanks
karthik
I'm currently trying to implement a Dropdown List with what I would assume is hardcoded values. Basically what I want is to have a Dropdown List with a choice of three possible values.
I have a total of 4 controllers and views that will be using this dropdown. I've seen a lot of examples for MVC2 and MVC3 where people have hard coded their dropdowns in their views, and I personally don't prefer to go with a quick and "dirty" fix such as that.
I have a model containing the following.
public class Status
{
public int id { get; set; }
public string status { get; set; }
public Status(int statusId, string statusName)
{
id = statusId;
status = statusName;
}
}
The status should be able to have any of the 3 possible values:
Active
Inactive
Processing
I thought of creating the status' using this method I currently have in my status class:
public static List<Status> getAllStatus()
{
List<Status> states = new List<Status>();
states.Add(new Status(1, "Active"));
states.Add(new Status(2, "Inactive"));
states.Add(new Status(3, "Processing"));
return states;
}
I haven't been able to figure out how to use this model inside my Controllers alongside with how to pass it along to my views and was hoping someone in here would known how to do that?
EDIT1:
I guess I forgot to mention that I will be storing the selected value as a string in my database and that I am using a view which doesn't have the model of my status class, but rather the model of object which I will be storing in my database (which might be the case of a vehicle object).
EDIT2:
I have a model called Customer, which has some of the following values:
public int CustomerID { get; set }
public string Email { get; set }
public string Phone { get; set }
public Status Status { get; set; }
In my DB for my Customer model I have a string in which I wan to store the selected Status.
So basically I wan't to change the following to a dropdown with 3 options, Inactive, Active and Processing.
However I don't want to code this in my view as I will be needing it in 8 different views and copy pasting that is not very sleek code.
#Html.DropDownListFor(m => m.status_id, new SelectList(getAllStatus(), "id", "status"))
It doesn't make much sense to save it as a string within your database as it sounds more like something static. So u should consider an Enum. To me more precise look to my previous answer and add those Model properties to a ViewModel.
public class CustomerViewModel () {
public int SelectedStatusId { get; set; }
[DisplayName("Status")]
public IEnumerable<SelectListItem> StatusItems
{
get
{
yield return new SelectListItem { Value = "", Text = "- Select a status -" };
StatusTypeEnum[] values = (StatusTypeEnum[])Enum.GetValues(typeof(StatusTypeEnum));
foreach (StatusTypeEnum item in values)
{
if (item != StatusTypeEnum.Unknown)
{
yield return new SelectListItem { Value = ((int)item).ToString(), Text = item.GetDescription() };
}
}
}
}
}
Pass this into your View through your controller:
public class CustomerCOntroller(){
public ActionResult Index(){
CustomerViewModel viewModel = new CustomerViewModel();
return View(viewModel);
}
}
And you are done. If u are more working with a list which u need to build up add it to your viewModel object.
Greetings,
S..
To start you have a lot of vague questions. Be more specific if you can. If you don't know how MVC works that well I would recomment to follow some tutorials on it.
Model.cs (A ViewModel is preferred). You Should create a ViewModel which you passes to the View. Below is an example how to get a list of items.
public int SelectedStatusId { get; set; }
[DisplayName("Status")]
public IEnumerable<SelectListItem> StatusItems
{
get
{
yield return new SelectListItem { Value = "", Text = "- Select a status -" };
StatusTypeEnum[] values = (StatusTypeEnum[])Enum.GetValues(typeof(StatusTypeEnum));
foreach (StatusTypeEnum item in values)
{
if (item != StatusTypeEnum.Unknown)
{
yield return new SelectListItem { Value = ((int)item).ToString(), Text = item.GetDescription() };
}
}
}
}
StatusTypeEnum.cs
public enum StatusTypeEnum()
{
[Description("Active")] // For correct naming
Active,
Inactive,
Processing
}
View.cshtml
#Html.DropDownListFor(x => Model.SelectedStatusId, Model.StatusItems)
EnumAttribute.cs (To read the Annotation Descriptions. And don't try to understand this. It's just magic. It gets the DataAnnotation of the enum types by reflection.)
public static class EnumAttribute
{
public static string GetDescription<TEnum>(this TEnum value)
{
var fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
}
return value.ToString();
}
}
You could declare States as public propery in your class and use this to access it in your views:
<ComboBox Grid.Column="1" Grid.Row="0" Margin="5"
VerticalAlignment="Center" ItemsSource="{Binding States}"
IsTabStop="False"}"/>
I've been struggling to research an answer to this question as I cannot come up with the correct search terms.
Basically I have 2 IEnumerable<T>'s in my controller, below is the code for the attempt I made.
Controller:
IEnumerable<Room> allRooms = RoomHelper.FindAllRooms();
foreach (var room in allRooms)
{
IEnumerable<Bunk> associatedBunks = RoomHelper.FindAssociatedBunksByRoom(room);
if (associatedBunks.Count() > 0)
{
ViewData["Room_"+room.RoomId] = associatedBunks;
}
}
And I'm trying to send them to the view in a way that I can do two foreach loops that will cycle through one set of data (in this case the Room objects and will then using the Room.RoomId key cycle through another IEnumerable which contains the associated data.
My view looks like this but is showing parse errors:
#foreach (var room in ViewBag.Rooms)
{
<h2>#room.RoomName</h2>
#if (ViewData["Room_" + room.RoomId].Count() > 0)
{
<ol>
#foreach (var bunk in ViewData["Room_" + room.RoomId])
{
<li>#bunk.BunkId</li>
}
</ol>
}
}
The end result I'm looking for in the HTML is something like:
<h2>Room 1</h2>
<ol>
<li>Bunk 1</li>
<li>Bunk 2</li>
</ol>
<h2>Room 2</h2>
<ol>
<li>Bunk 3</li>
<li>Bunk 4</li>
</ol>
What is the best practice in ASP.NET MVC 4 with EF5 to achieve this kind of result when passing "multidimensional" (is this multidimensional?) data?
Don't rely on ViewData. Store the data that you want to pass on to your view in a proper ViewModel:
public class RoomViewModel
{
List<Room> Rooms { get; set;}
...
}
Store your data in one of those.
Your Controller method then returns an instance of it:
public RoomViewModel GetRooms(int someParameter)
{
RoomViewModel result = new RoomViewModel();
result.Rooms = RoomHelper.Something(someParameter);
...
return result;
}
Your View declares its model on top:
#model MyApplication.ViewModels.RoomViewModel
and hence you use it in your View.
<h2>#Model.Rooms.Count rooms found</h2>
etc.
Use a code block in your view instead of adding an '#' in front of each C# statement:
#{
foreach (var room in ViewBag.Rooms)
{
#Html.Raw("<h2>" + room.RoomName + "</h2>");
if (ViewData["Room_" + room.RoomId].Count() > 0)
{
#Html.Raw("<ol>");
foreach (var bunk in ViewData["Room_" + room.RoomId])
{
#Html.Raw("<li>" + bunk.BunkId + "</li>");
}
#Html.Raw("</ol>");
}
}
}
You should avoid the use of #HtmlRaw("") as far as possible as it has a XSS vulnerability. But this should put you on the right track.
As per description given by you it seems that Bunk is associated with rooms. If that's the case then Bunk may have some id for pointing to room it belongs. Now you can create a ViewModel like this
public class BunkViewModel:Bunk
{
public BunkViewModel()
{
Mapper.CreateMap<Bunk,BunkViewModel>();
}
//I'm assuming that you already have some id in bunk to point to room it belongs.
//But writing it here to make it clear
public int RoomId { get; set; }
public string RoomName { get; set; }
//Use AutoMapper to Map
public static BunkViewModel Map(Bunk source)
{
return Mapper.Map<Bunk,BunkViewModel>(source);
}
}
Now in your controller
public ActionResult ActionName()
{
var result = new List<BunkViewModel>();
var rooms = RoomHelper.FindAllRooms();
var bunks = BunkHelper.GetAllBunks();
foreach(var bunk in bunks)
{
var bunkViewModel = BunkViewModel.Map(bunk);
var room = rooms.FirstorDefault(r=>room.RoomId == bunk.RoomId);
bunkViewModel.RoomId = room.RoomId; //No need to set if you already have this id in bunk
bunkViewModel.RoomName = room.RoomName;
result.Add(bunkViewModel);
}
return View(result.);
}
Now in your view you can do like this
#model List<MyApplication.ViewModels.RoomViewModel>
#foreach(var bunk in Model)
{
//Print it here as you want..
}
I have my enum like this.
public enum Gender
{
Man = 1,
Woman = 2
}
And I use ASP MVC4 to display the choices in a drop down like this.
#Html.DropDownListFor(model => model.Gender, new SelectList(Enum.GetValues(typeof(Namespace.Models.Enum.Gender))))
This works like a charm, it display Man/Woman in the drop down.
My problem is that I would like to show different names on those enums in different contexts.
Like one context would be if you are a Mom or a Dad. I would like to use the gender enum as base, but display Mom/Dad instad of Man/Woman.
Another context would be Boy/Girl, I still would like to use the gender enum, but display a different text.
Is this possible in any way?
EDIT
I used Kevin's solution and also added another extention method like this.
public static List<KeyValuePair<string, int>> GetValues(IGenderStrategy genderStrategy)
{
Dictionary<string, int> arr = new Dictionary<string, int>();
foreach (Gender g in System.Enum.GetValues(typeof(Gender)))
arr.Add(g.ToValue(genderStrategy), (int)g);
return arr.ToList();
}
Which I used like this in my view.
#Html.DropDownListFor(model => model.Gender, new SelectList(Chores.Models.Enum.EnumExtentions.GetValues(new Chores.Models.Enum.ParentStrategy()), "value", "key"))
I like #RakotVT answer of using an extension method but would extend it a bit further as you would need a new extension method for every situation which is not great.
I think a variation of the Strategy pattern might work better here (http://www.dofactory.com/Patterns/PatternStrategy.aspx)
Something like this -
public enum Gender
{
Man = 1,
Woman = 2
}
public interface IGenderStrategy
{
string DisplayName(Gender gender);
}
public class ParentStrategy : IGenderStrategy
{
public string DisplayName(Gender gender)
{
string retVal = String.Empty;
switch (gender)
{
case Gender.Man:
retVal = "Dad";
break;
case Gender.Woman:
retVal = "Mom";
break;
default:
throw new Exception("Gender not found");
}
return retVal;
}
}
public static class EnumExtentions
{
public static string ToValue(this Gender e, IGenderStrategy genderStategy)
{
return genderStategy.DisplayName(e);
}
}
public class Test
{
public Test()
{
Gender.Man.ToValue(new ParentStrategy());
}
}
Try to add Extentions class for your Enum. Here is an example of this class.
public static class EnumExtentions
{
public static string ToChildValue(this Gender e)
{
string retVal = string.Empty;
switch (e)
{
case Gender.Man:
retVal = "Boy";
break;
case Gender.Woman:
retVal = "Girl";
break;
}
return retVal;
}
public static string ToParentValue(this Gender e)
{
string retVal = string.Empty;
switch (e)
{
case Gender.Man:
retVal = "Dad";
break;
case Gender.Woman:
retVal = "Mom";
break;
}
return retVal;
}
}
Dunno if this is the neatest way, but how about something like:
#functions{
IEnumerable<SelectListItem> GetGenderSelectList(GenderContext genderContext)
{
return Enum.GetValues(typeof(Namespace.Models.Enum.Gender)).ToList().ConvertAll(x => new SelectListItem(){Value= x.ToString(), Text= GetGenderDescription(x, genderContext)});
}
string GetGenderDescription(Gender gender, GenderContext genderContext)
{
switch (GenderContext)
{
case Children: return gender == Man? "Boy" : "Girl";
case Parents: return gender == Man? "Dad" : "Mom";
default: return gender.ToString();
}
}
}
#Html.DropDownListFor(model => model.Gender, GetGenderSelectList(model.GenderContext))
Here 'GenderContext' is another Enum.
obviously you don't need to have those functions in the page functions - Could just add the list of items to the ViewBag before even getting to the view.