Skip to content

Instantly share code, notes, and snippets.

@graylikeme
Created July 27, 2011 17:31
Show Gist options
  • Save graylikeme/1109933 to your computer and use it in GitHub Desktop.
Save graylikeme/1109933 to your computer and use it in GitHub Desktop.
Snippets for "Model Binding Collections on Postback in ASP.NET MVC3" blog post
namespace Example
{
public class ContactData
{
public string Name { get; set; }
public string Email { get; set; }
public string Comment { get; set; }
}
}
[HttpPost]
public ActionResult Index(ContactData contactData)
{
if(ModelState.IsValid)
{
//do something here
}
return View(contactData);
}
@model ContactData
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<div>
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Name) <br />
@Html.TextBoxFor(x => x.Name) <br />
@Html.LabelFor(x => x.Email) <br />
@Html.TextBoxFor(x => x.Email) <br />
@Html.LabelFor(x => x.Email) <br />
@Html.TextBoxFor(x => x.Email) <br />
@Html.LabelFor(x => x.Comment) <br />
@Html.TextAreaFor(x => x.Comment) <br />
<input type="submit" id="btnSubmit"/>
}
</div>
</body>
</html>
@using Example
@model IEnumerable<PollData>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<div>
@using (Html.BeginForm())
{
foreach (var contactData in Model)
{
<label>@contactData.Question</label>
@Html.HiddenFor(x => contactData.Question) <br />
@Html.TextBoxFor(x => contactData.Answer) <br />
}
<input type="submit" id="btnSubmit"/>
}
</div>
</body>
</html>
[HttpPost]
public ActionResult Index(IEnumerable<PollData> pollData)
{
if(ModelState.IsValid)
{
//do something here
}
return View(pollData);
}
@using Example
@model IList<PollData>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<div>
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Count(); i++)
{
<label>@Model[i].Question</label>
@Html.HiddenFor(x => x[i].Question) <br />
@Html.TextBoxFor(x => x[i].Answer) <br />
}
<input type="submit" id="btnSubmit"/>
}
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment