ASP.NET MVC2 TeplatedHelper doesn't render an ID of the HTML's markup - asp.net-mvc-2

I have the code (snippet):
The Model is the IEnumerable object of the Person's class:
<% foreach (var item in Model)
{ %>
<tr>
<td><%= Html.DisplayFor(x=>item.Name) %></td>
</tr>
<% } %>
it renders only labels like that:
<td>Tommy</td>
According to the link it should be rendering a HTML markup something like:
but there is no the ID and the NAME property. Why ?

Your using the wrong template your should be using Html.EditorFor(x => x.Name)
Edit: I said you were using the wrong template because in your image it is a textbox displayed, not a label...
the default ouptut of Displayfor is
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.Encode(ViewData.TemplateInfo.FormattedModelValue) %>
according to Brad Wilson. You could easily build your own, look the other post of Brad Wilson for examples.
Or you could simply call Html.LabelFor(x => x.Name)
If you always want that, add a template, name String.ascx in your Views/Share/DisplayTemplate and just put the following in :
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.Label("", ViewData.TemplateInfo.FormattedModelValue) %>

Related

Simple foreach loop in MVC

<% foreach (var car in Model.AvailableCars)
{ %>
<label><%car.Text; %></label>
<% } %>
The above code throws the error
Only assignment, call, increment, decrement, and new object expressions can be used as a statement.
I know I can do it with html helpers, but why won't the above code work?
<label><%car.Text; %></label>
should read
<label><%= car.Text; %></label>
^
or you can use
<label><%: car.Text; %></label>
^
which will automatically HTML.Encode the value for you.
Add a colon to the car.Text tag to write it to the document, such as:
<label><%: car.Text %></label>
Here's a good explanation of <%: versus <%= asp.net mvc tags: <%: %> vs. <%= %>

How to access my model from my view?

I cannot seem to figure out how to access my Model from my View. I am confused.
Here is my Home controller. I have verified that "specimens" is being populated with data from the database:
public class HomeController : Controller
{
wildtropEntities wildlifeDB = new wildtropEntities();
public ActionResult Index()
{
ViewData["CurrentDate"] = System.DateTime.Now.ToString("MM/dd/yyyy");
var specimens = from s in wildlifeDB.specimen1
select s;
return View(specimens);
}
}
And here are couple snippets from my View:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<% foreach (WildlifeTropical.Models.specimen s in ??????)
{ %>
<div>s.Name</div>
<% } %>
I assumed I would be able to access "specimens" since I passed it to the View from the Controller (ie, return View(specimens))...but it isn't working.
You will have to make your view strongly typed to a collection of specimen which is what you are passing to it from your controller action (IEnumerable<specimen>):
<%# Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<WildlifeTropical.Models.specimen>>" %>
<% foreach (WildlifeTropical.Models.specimen s Model) { %>
<div><%= Html.Encode(s.Name) %></div>
<% } %>
Notice how the view inherits System.Web.Mvc.ViewPage<IEnumerable<WildlifeTropical.Models.specimen>> and it is now strongly typed to a collection of specimens that you will be able to loop through.
This being said, personally I don't like writing foreach loops in my views. They make them look ugly. In this case I would use a display template:
<%# Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<WildlifeTropical.Models.specimen>>" %>
<%= Html.DisplayForModel() %>
and then I would define a display template which will automatically be rendered for each element of the model collection (~/Views/Shared/DisplayTemplates/specimen.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<WildlifeTropical.Models.specimen>" %>
<div>
<%= Html.DisplayFor(x => x.Name) %>
</div>
See how the specimen.ascx user control is now strongly typed to System.Web.Mvc.ViewUserControl<WildlifeTropical.Models.specimen>. This is because it will be rendered for each specimen of the main view model.
I am not sure about MVC2. In MVC 3(with Razor View Engine), I can pass the Model / ViewModel to the View like this.
#model MyProject.ViewModel.UserViewModel
#{
ViewBag.Title = "Welcome To My Site";
}
<div class="divSubHead">
<h2>Hello #Model.FirstName</h2></div>
How about this? Note the Inherits for the Page.
<%# Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of IEnumerable(Of Specimen))" %>
<% foreach (WildlifeTropical.Models.specimen s in Model)
{ %>
<div>s.Name</div>
<% } %>

What is difference between these tags <% <%: <%= in ASP.NET MVC 2?

The title contain my whole question.
<% /* Is a codeblock */ for(int i = 0;i<5;i++) { } %>
<%= "Writes something to the output stream" /* Response.Write */ %>
<%: "HTML-encodes this <b>hello</b> to the output stream" %>
For a good explanation about the <%, <%= and <%# syntax and their usage, please read this article.
The <%: syntax is new in .Net 4 and is used for encoding HTML output. See this article of ScottGu for more information about that.
<% %> is used just to execute server side code
ex. <% if(oject){...} %>
<%= %> is used execute server side code and return value
ex. <%=Html.Encode(Item["Name"]) %>
<%: %> is used execute server side code but it will return Html
Encoded string
ex. <%Item["Name"] %>
Source : What is difference between these tags <%, <%: , and <%= in ASP.NET MVC 2?

How to Add, Edit and Display one to many relationship entities in ASP.Net MVC 2?

I am looking for best practices conforming to the MVC design pattern.
My Entities have the following relationship.
tblPortal PortalId PrortalName
tblPortalAlias AliasId PortalId HttpAlias
Each Portal can have many PortalAlias.
I want to Add a New Portal and then Add the associated PortalAlias.
I am confused on how I should structure the Views and how I should present the Views to the user. I am looking for some sample code on how to accomplish this.
My thoughts are first present the Portal View, let the user add the Portal. Then click the Edit link on the Portal List View and on the Portal Edit View let them Add the PortalAlias.
If so, what should the Edit View look like?
So far I have:
Edit View
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyProject.Mvc.Models.PortalFormViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Edit</h2>
<% Html.RenderPartial("PortalForm", Model); %>
<div>
<%= Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
PortalForm
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyProject.Mvc.Models.PortalFormViewModel>" %>
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.Portal.PortalId) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Portal.PortalId) %>
<%= Html.ValidationMessageFor(model => model.Portal.PortalId) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Portal.PortalName) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Portal.PortalName) %>
<%= Html.ValidationMessageFor(model => model.Portal.PortalName) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
Alias<br /><%-- This display is for debug --%>
<% foreach (var item in Model.PortalAlias) { %>
<%= item.HTTPAlias %><br />
<% } %>
PortalFormViewModel
public class PortalFormViewModel
{
public Portal Portal { get; private set; }
public IEnumerable<PortalAlias> PortalAlias { get; private set; }
public PortalFormViewModel()
{
Portal = new Portal();
}
public PortalFormViewModel(Portal portal)
{
Portal = portal;
PortalAlias = portal.PortalAlias;
}
}
Hopefully you've found an answer to this elsewhere, although based on how difficult it is to find information about this online, it's probably unlikely ...
An MSDN blog linked over to ASP.NET MVC, Entity Framework, Modifying One-to-Many and Many-to-Many Relationships (there's a link to the previous in the series in the first paragraph).
But Editing a variable length list, ASP.NET MVC 2-style seems a little better (and includes sample code).

Simple Asp.Net MVC2 Binding question: How to get an EditorFor to render a Radio Button Group?

Just thinking out loud about the subject, If I have the following:
<%= Html.EditorFor(m => m.Gender, "Gender")
And I want it to render two radio buttons:
O Male O Female
Assuming the class just has a string to hold the value, what would the Gender.ascx look like if we were to pass the Gender values using something like
ViewData["Gender"] = new string[] {"Male", "Female"};
This is a Radio button example (Yes No):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.RadioButton("", "Yes") %> Yes
<%= Html.RadioButton("", "No") %> No
And another Radio Button set (Gender):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.RadioButton("", "Male") %> Male
<%= Html.RadioButton("", "Female") %> Female
And a Drop Down Menu (Marital Status):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.DropDownList("", new SelectList(new[] {"N/A",
"Single", "Married", "Divorced", "Widowed" })) %>
Now I need to modify these to look for a matching ViewData[""] list of options or figure out how to pass a selection list to the partial UI Template.