Convert DateTime to Date - asp.net-mvc

Code:
<% foreach (var item in Model) { %>
<td>
<%= Html.Encode(item.BirthDate) %>
</td>
<% } %>
display this: 8/24/2009 12:00:00 AM but I need only date (8/24/2009). It is possible to do without any formating in controller action

There are a couple of ways to go about it. If you're using MVC 2, you could use a DisplayTemplate. Just put a DateTime.ascx file in the folder called /Views/Shared/DisplayTemplates and the line of code it would have in it is:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%: Model.HasValue ? Model.Value.ToShortDateString() : string.Empty %>
(Note: if you use the <%: syntax then you don't need the Html.Encode() because <%: does the HTML encoding for you - but that's only if you're using VS2010. If you're using MVC 2 with VS2008, then stick with the Html.Encode() for this part) Then in your view you would simply do this:
<%: Html.DisplayFor(m => m.BirthDate) %>
That will change the format to only have the Date for all DateTime's in your application. Of course you could put that directly in the view as well. But the DisplayTemplate will change it for all other DateTime's as well and you won't have to concern yourself with it in the view since it happens for your automatically.

If BirthDate is string datatype
<%= Html.Encode(!String.IsNullOrEmpty(item.BirthDate) ?
Convert.ToDateTime(item.BirthDate).ToShortDateString() : item.BirthDate) %>
If BirthDate is datetime datatype
<%=Html.Encode(String.Format("{0:MM/dd/yyyy}", item.BirthDate))%>

I would say that formatting is a responsibility of the view, not the controller, so format the output like this:
<% foreach (var item in Model) { %>
<td>
<%= Html.Encode(item.BirthDate.ToShortDateString() %>
</td>
<% } %>

If item.BirthDate is type of DateTime you can use ToShortDateString() method:
item.BirthDate.ToShortDateString();

<% foreach (var item in Model) { %>
<td>
<%= Html.Encode(item.BirthDate.ToString("MM/dd/yyyy")) %>
</td>
<% } %>

Related

Hide Html.TextBoxFor on condition

I have an ASP.NET MVC2 application. On one of my pages I have a textbox defined in the following manner:
<%: Html.TextBoxFor(model => model.PostCode) %>
Which is working perfectly.
However, for specific countries (model.Country) I do not want to show this TextBox.
What is the best way of implementing this?
This is an .aspx file, not .cshtml
Thanks
Create a property in your model class, and try this:
#if (!Model.IsSpecificCountry) {
#Html.TextBoxFor(model => model.PostCode)
}
Update:
<%if (!Model.IsSpecificCountry) { %>
<%= Html.TextBoxFor(model => model.PostCode) %>
<% } %>

Persist Values for DropDownList Editor Templates

I have this on my view and this works well, persisting the country selected:
<%: Html.DropDownListFor(model => model.CountryId, Model.CountryList ,"Select Country") %>
However when I create an editor template for this, the country selected is not persisted
So, I change my current view to this:
<%: Html.EditorFor(model => model.CountryId,new { countries = Model.CountryList}) %>
Then I create my editor template like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Int64?>" %>
<%= Html.DropDownList(
String.Empty /* */,
(SelectList)ViewData["countries"],
Model
)
%>
I would try something like this:
Code in parent view:
<% Html.RenderPartial("YourPartialView", Model) %>
Code in editor view:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ModelFromParent>" %>
<%= Html.DropDownList(
String.Empty /* */,
new SelectList(Model.Countries,"Id", "Title"),
"Select Country"
)
%>
I didn't compile this. But you get the general idea.

Weird error in strongly-typed MVC2 view

The ViewUserControl below results in the following error at runtime:
The Collection template was used with an object of type 'System.Data.Entity.DynamicProxies.Collection_1D9779ACB92AE24E3428C288EA7B1480A6477CF8861FB7582692E775613EFB3A', which does not implement System.IEnumerable.
The error occures on this line: <%: Html.EditorFor(model => model) %>
If I change the name of the model object to Collection2 it works. Does it gets confused because Collection is also the name of an object in the .net framework?
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CollectionManager.Models.Collection>" %>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true) %>
<%: Html.EditorFor(model => model) %>
<input type="submit" value="Save" />
<% } %>
remco - yes, i think that would definately be a reserved word. not sure about it getting confused but definately you should take care with naming when potential clashes could occur. the same thing is true of variable names, tho you can prefix them with # to override that i.e. string #absract would be allowable, whereas string abstract wouldn't.
go with the 'reserved' flow :)
jim

linq groupby in strongly typed MVC View

How do i get an IGrouping result to map to the view?
I have this query:
var groupedManuals = manuals.GroupBy(c => c.Series);
return View(groupedManuals);
What is the proper mapping for the ViewPage declaration?
Inherits="System.Web.Mvc.ViewPage<IEnumerable<ProductManual>>"
I am still in the early stages of learning Linq so I may be wrong but I think that that ViewPage will need to be something like
Inherits="System.Web.Mvc.ViewPage<IEnumerable<IGrouping<Series, Manual>>>
In the instance of helping others out. This is what I was attempting to accomplish.
The action code
var groupedManuals = manuals.GroupBy(c => c.Series);
return View(groupedManuals);
The View
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<IGrouping<string, ProductManualModel>>>" %>
<% foreach (var item in Model)
{ %>
<div class="manual-category">
<h5>
<%= Html.Encode(item.Key) %> Series</h5>
<ul>
<% foreach (var m in item)
{ %>
<li><a href="<%=Url.ManualLink(m.Id) %>" class="model-manuals">
<%= m.Id %></a> </li>
<% } %>
</ul>
</div>
IGrouping is a list of lists so to speak. With the "Key" being the grouped property in the source list.
The view must be the same type of the page. You would have to convert the output to the same type used by your view page.
You could also use a ViewData["Products"] to set the collection information you want to be visible on your View aspx page.

How to show the List returned to view by controller?

I am using VS 2008 MVC.
I developed a controller.
Form controller i fetch the data by using LinqToSql.
& i am retuning a list of that data.
e.g. return View(Students.Tolist());
now i want to display the list using "foreach" loop in view.
so how do i achieve it?
You return your Student list in the Controller Action as the Model for the View, so make sure your View is strongly typed. Your View should have this at the top:
Inherits="System.Web.Mvc.ViewPage<List<Your.Namespace.Student>>"
Then you can iterate over that list in the View like this:
<% foreach(var student in Model)
{ %>
<div class="student">
<%= student.Name %>
<%= student.Age %>
</div>
<% } %>
This is if you use the MVC RC or newer.
You should have a Student class to hold the records outputted by LINQ to SQL. Anonymous types don't work well in this scenario.
<% foreach (var item in (IEnumerable<Student>)ViewData.Model) { %>
<div class="student">
Name: <%= item.Name %> <br />
GPA: <%= item.GPA %>
</div>
<% } %>

Resources