Reputation: 1003
I am trying to do something that I think is relatively simple but can't get it to work and would be greatful for some pointers.
I've got a form with a list of text boxes in it... Lets say, I want to find out "Your Favourite Pirates", and get you to list all ten on the page with comments as to why they are your favourite.
So in my view I have:
for (int i =1; i <11; i++)
{%>
<%=Html.TextBoxFor(x => x.Pirate + i, new { size = 30, maxlength = 200 })%>
<%=Html.TextAreaFor(x => x.PirateReason + i, new { cols = 42, rows = 2 })%>
<%
}%>
But how do I set this up in my model?
Sorry if it wasn't specific.
In my model I just want to store the list of pirates, in the example that I am currently working on there are only 10 pirates so I COULD do it like this if I had to
public string Pirate1 { get; set; }
public string Pirate2 { get; set; }
public string Pirate3 { get; set; }
public string Pirate4 { get; set; }
public string Pirate5 { get; set; }
public string Pirate6 { get; set; }
public string Pirate7 { get; set; }
public string Pirate8 { get; set; }
public string Pirate9 { get; set; }
public string Pirate10 { get; set; }
But that's horrible, what if I wanted to know your fav 100 Pirates?
I want to store the pirates in the model so I can either pop them in a database or send as an email...
Many thanks for your advice..
Upvotes: 2
Views: 1874
Reputation: 1038850
Model:
public class Pirate
{
public int Id { get; set; }
public string PirateReason { get; set; }
}
Controller action:
public ActionResult Index()
{
var model = Enumerable
.Range(1, 11)
.Select(i => new Pirate {
Id = i,
PirateReason = string.Format("reason {0}", i)
});
return View(model);
}
Strongly typed view to IEnumerable<Pirate>
:
<%= Html.EditorForModel() %>
Editor Template (~Views/Shared/EditorTemplates/Pirate.ascx
):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeNs.Pirate>" %>
<%= Html.TextBoxFor(x => x.Id, new { size = 30, maxlength = 200 }) %>
<%= Html.TextAreaFor(x => x.PirateReason, new { cols = 42, rows = 2 }) %>
Upvotes: 1