I followed this tutorial to add & remove multiple textbox: http://www.itorian.com/2013/04/nested-collection-models-in-mvc-to-add.html. I want to know how to use multiple templates for "EditorFor".
In my Chemical model:
public partial class NPG_Chemical
{
public NPG_Chemical()
{
this.NPG_Chemical_Measurement_Methods = new HashSet<NPG_Chemical_Measurement_Method>();
}
public virtual ICollection<NPG_Chemical_Measurement_Method> NPG_Chemical_Measurement_Methods { get; set; }
internal void CreateMeasurementMethods(int count = 1)
{
for (int i = 0; i < count; i++)
{
NPG_Chemical_Measurement_Methods.Add(new NPG_Chemical_Measurement_Method());
}
}
In my Chemical controller:
public ActionResult Create()
{
var nPG_Chemical = new NPG_Chemical();
nPG_Chemical.CreateMeasurementMethods(1);
return View(nPG_Chemical);
}
In my Create.cshtml:
<div id="type1s">
<label>
Type1:
</label>
#Html.EditorFor(model => model.NPG_Chemical_Measurement_Methods)
</div>
<div id="type2s">
<label>
Type2:
</label>
#Html.EditorFor(model => model.NPG_Chemical_Measurement_Methods)
</div>
and I have a template: NPG_Chemical_Measurement_Method.cshtml
#model NPG_Administrative_Utility.Models.NPG_Chemical_Measurement_Method
<div class="type1" style="display:inline-block;">
<p>type1
#Html.Hidden("Measurement_Type", "Type1")
#Html.TextBoxFor(x => x.Measurement_Method)
</p>
</div>
The problem is how can I use another template which include the following code for type 2 EditorFor:
#model NPG_Administrative_Utility.Models.NPG_Chemical_Measurement_Method
<div class="type2" style="display:inline-block;">
<p>type2
#Html.Hidden("Measurement_Type", "Type2")
#Html.TextBoxFor(x => x.Measurement_Method)
</p>
</div>
Now these two EditorFor will all use the first template.
I believe what you want is a partial view.
Related
Index.cshtml code for text box
#Html.LabelFor(m => m.ValidFromDate, "ValidFromDate")
#Html.TextBoxFor(m => m.ValidFromDate)
I don't get idea how to insert this text box value to database
Let's assume you have a table names Users in the db. First we will create a POCO which will represent this table as follows:
public class User
{
public string Username { get; set; }
public DateTime ValidFromDate { get; set; }
//more propteries
}
Now let's assume we have a view named Create. In this view you will pass the User class we've created as your model. So your view should look something like this.
#model Models.User
#{
ViewBag.Title = "User";
}
<div>
#using (Html.BeginForm("Create", "User"))
{
#Html.AntiForgeryToken()
#Html.LabelFor(m => m.Username)
#Html.TextBoxFor(m => m.Username)
#Html.LabelFor(m => m.ValidFromDate)
#Html.TextBoxFor(m => m.ValidFromDate)
<button type="submit">Submit</button>
}
</div>
Now you want to get all the values from this view inside your controller action. We will go ahead and create a controller named UserController and inside this controller we will provide GET and POST methods our Create
//This is our GET action for the view
public ActionResult Create()
{
User user = new User();
return View(user); //we pass in the user object to the view
}
[HttpPost]
[ValidateAntiForgeryToken]
//when you click submit this is the action that will get hit
public ActionResult Create(User model)
{
if (!ModelState.IsValid)
return View(model);
string userName = model.Username;
DateTime validFrom = model.ValidFromDate;
//save to db here. I'm not sure if you're making direct calls or using entity framework or similar framework
return RedirectToAction("Index", "Home"); //this will redirect the user to home. You can return a view or redirect user somewhere else.
}
Here we go . I tested this and it returned me the model properties along with files posted .
//-- this is the controller
public class FileUploadDemoController : Controller
{
//
// GET: /FileUploadDemo/
public ActionResult Index()
{
return View();
}
-- here you can name the method as you like to I justuse postform
[HttpPost]
public ActionResult PostForm(FileUploadModel model)
{
Request.Files is the object which contrins all files which you posted from the form when you hit submit buuton after selecting excel file.
if (Request.Files != null && Request.Files.Count > 0)
{
// here you have files attached and model propertied now you can go to db and perform operation which you need to do
}
return View("Index", model);
}
}
-- This is the model which I use to bind the form
namespace WebApplication1.Models
{
public class FileUploadModel
{
public string Name { get; set; }
public string ValidFromDate { get; set; }
}
}
-- Finaly the cshml file . The import point is to use new { enctype = "multipart/form-data" } inside BeginForm .
// the page from where you will post the data . Please change you model class in place of FileUploadModel I created ot for me .
// Please not I didnt not use any datepicket to keep it simple if you enter date like 01-01-2015 this to test .
#model WebApplication1.Models.FileUploadModel
#using (Html.BeginForm("PostForm", "FileUploadDemo", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="panel">
<div class="panel-body">
<div class="form-group row">
<div class="col-md-2 form-label">
<label>Name:</label>
</div>
<div class="col-md-6">
#Html.TextAreaFor(x => x.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group row">
<div class="col-md-2 form-label">
<label>Date</label>
</div>
<div class="col-md-6">
#Html.TextAreaFor(x => x.ValidFromDate, new { #class = "form-control" })
</div>
</div>
<div class="col-md-10">
<div class="form-group row">
<div class="col-md-2 form-label">
<label>Select File<i class="required-field">*</i>:</label>
</div>
<div class="col-md-8">
<input type="file" class="file-upload" style="margin: 0px;" hidden="hidden" accept=".xlsx" name="file" id="file" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-3 pull-right text-right">
<button class="btn btn-primary" id="process-submission" type="submit"
>Submit</button>
</div>
</div>
</div>
</div>
}
How can I display two partial views in the same view? In my controller I have two methods that both returns partialview. I want these methods together in one view.
In my controller i have this:
public ActionResult CountCars()
{
var result = this.Data.Cars.All()
.Select(t => new CarsViewModel
{
CategoryName = t.Name,
CategoryCount = t.Category.Count()
});
return PartialView("_ChooseCarsPartialViewLayout", result.ToList());
}
public ActionResult ChooseCity()
{
var view = this.Data.Cities.All()
.Select(x => new CityViewModel
{
CityName = x.Name,
CountCities = x.City.Count()
});
return PartialView("_ChooseCarsPartialViewLayout", view.ToList());
}
_ChooseCarsPartialViewLayout
#model IEnumerable<Project.ViewModels.City.CityViewModel> <div class="container">
<div class="well">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<h4>?</h4>
<div class="checkbox checkbox-primary">
#for (int i = 0; i < Model.Count(); i++)
{
var cars = Model.ElementAt(i);
<label>#cars.CategoryName <span class="badge">#cars.CategoryCount</span></label>
#Html.RadioButton(cars.CategoryName,
cars.CategoryId,
new
{
id = "radio",
type = "checkbox"
})
}
</div>
</div>
<div class="form-group">
<h4>Hvor vil du jobbe?</h4>
<div class="checkbox checkbox-primary">
#for (int i = 0; i < Model.Count(); i++)
{
var city = Model.ElementAt(i);
<label>#city.CityName <span class="badge">#city.CountCities</span></label>
#Html.RadioButton(city.CityName,
city.CityId,
new
{
id = "radio",
type = "checkbox"
})
}
</div>
</div>
</div>
</div>
</div>
And when I run the solution it just display an error that says.
Value cannot be null or empty.
Parameter name: name
Line 18: #Html.RadioButton(cars.CategoryName,
But if I had two different partial views then it works great, but I want to have this in the same partialview.
Also I have this Html.Action in _Layout to render the partialviews
#Html.Action("ChooseCity", "Home")
Any suggestion?
Problem is with the partial view model which is strongly typed of IEnumerable<Project.ViewModels.City.CityViewModel> which does not contain the declaration of CategoryName. So, you should create a Composite Model which would return Cars and Citis to partial view.
public class CompositeModel
{
public IEnumerable<Project.ViewModels.City.CityViewModel> Cars { get; set; }
public IEnumerable<Project.ViewModels.City.CarsViewModel> Cities { get; set; }
}
Now change your view as
#model CompositeModel
<div class="container">
<div class="well">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<h4>?</h4>
<div class="checkbox checkbox-primary">
#for (int i = 0; i < Model.Cars.Count(); i++)
{
var cars = Model.Cars.ElementAt(i);
<label>#cars.CategoryName <span class="badge">#cars.CategoryCount</span></label>
#Html.RadioButton(cars.CategoryName,
cars.CategoryId,
new
{
id = "radio",
type = "checkbox"
})
}
</div>
</div>
<div class="form-group">
<h4>Hvor vil du jobbe?</h4>
<div class="checkbox checkbox-primary">
#for (int i = 0; i < Model.Cities.Count(); i++)
{
var city = Model.Cities.ElementAt(i);
<label>#city.CityName <span class="badge">#city.CountCities</span></label>
#Html.RadioButton(city.CityName,
city.CityId,
new
{
id = "radio",
type = "checkbox"
})
}
</div>
</div>
</div>
</div>
</div>
Since you have a ViewModel called CityViewModel (though I'll name it RadiosVM I would create a few EditorFor templates.
Use a composite model as user1672994 mentioned in his answer although it can be made more generic and reusable. A ViewModel should encapsulate all (there are exceptions) the data necessary to render a view.
public class RadiosVM
{
public string Name { get; set; }
public IEnumerable<RadioVM> Radios { get; set; }
}
public class RadioVM
{
public string Name { get; set; }
public int Count { get; set; }
}
public class SomePageVM // whatever
{
public RadiosVM CarRadios { get; set; }
public RadiosVM CityRadios { get; set; }
// ... other properties
}
Don't spin up another controller just to display a model (that is inefficient), unless the controller is doing things that have absolutely nothing to do with the current controller and/or you plan on caching that view.
public class SomeController
{
public ActionResult SomePage()
{
var model = new SomePageVM();
model.CarRadios = GetCarRadios;
model.CityRadios = GetCityRadios;
return View(model);
}
private RadiosVM GetCarRadios()
{
var result = new RadiosVM()
{
Name = "Cars",
Radios = this.Data.Cars.All()
.Select(t => new RadioVM
{
CategoryName = t.Name,
CategoryCount = t.Category.Count()
})
.ToList();
}
return result;
}
public RadiosVM ChooseCity()
{
var result = new RadiosVM ()
{
Name = "Cars",
Radios = this.Data.Cities.All()
.Select(t => new RadioVM
{
CategoryName = t.Name,
CategoryCount = t.Category.Count()
})
.ToList();
}
return result;
}
Views:
SomePage.cshtml
#Model SomePageVM
<div class="well">
<div class="row">
<div class="col-md-12">
#Html.EditorFor(m => m.CarRadios)
<div/>
<div class="col-md-12">
#Html.EditorFor(m => m.CityRadios)
<div/>
// ...
/Views/Shared/EditorTemplates/RadiosVM.cshtml
or
/Views/SomeController/EditorTemplates/RadiosVM.cshtml
#Model RadiosVM
<div class="form-group">
<h4>#Html.DisplayFor(m => m.Name)</h4>
<div class="checkbox checkbox-primary">
#Html.DisplayFor(m => m.Radios)
</div>
/Views/Shared/EditorTemplates/RadioVM.cshtml
or
/Views/SomeController/EditorTemplates/RadioVM.cshtml
#Model RadioVM
<label>#Html.DisplayFor(m => m.Name)
<span class="badge">#Html.DisplayFor(m => m.Count)</span>
</label>
#Html.RadioButton(model.Name,
model.Id, // You have no code that references this, I don't know...
new
{
id = "radio", // so **ALL** radios are named 'id'?? not valid
type = "checkbox"
})
I am facing a problem for passing data to a controller.
I have a class that contains a list. I pass an instance of my object in my controller to retrieve my view. Which is actually a form. And when I submit my form, the object becomes empty, then there's that he depart at least two entries in the list. I have used the same method name to retrieve my data via Form.Method.
This is my code :
Model
public class XMLRecord
{
public string TypeDoc { get; set; }
public string Type { get; set; }
public string Contenu { get; set; }
public string DocName { get; set; }
public IEnumerable<XMLRecord> Records { get; set; }
}
View
#model ManageXML.Models.XMLRecord
<body>
#using (Html.BeginForm("HandleForm", "XMLRecord", FormMethod.Post, new { #class = "form-horizontal", #role = "form", #id = "FormCreateXML" }))
{
<fieldset>
<legend> XML Editor</legend>
#if (Model.Records == null)
{
<p>None</p>
}
else
{
<ul id="XmlEditor" style="list-style-type: none">
#foreach (var record in Model.Records)
{
Html.RenderPartial("XmlEditor", record);
}
</ul>
<button type="button" class="btn btn-default" id="addAnother">Add another</button>
}
</fieldset>
<p>
<button type="submit" class="btn btn-default">Save</button>
<button type="button" class="btn btn-default">Cancel</button>
</p>
}
</body>
Partial View
#model ManageXML.Models.XMLRecord
<li style="padding-bottom:15px" >
#using (Html.BeginCollectionItem("XmlRecords")) {
<img src="#Url.Content("~/Content/images/draggable.jpg")" height="20"width="20" style="cursor: move" alt=""/>
#Html.LabelFor(model => model.Type)
#Html.EditorFor(model => model.Type)
#Html.LabelFor(model => model.Contenu)
#Html.EditorFor(model => model.Contenu)
Delete
}
</li>
Controller
public class XMLRecordController : Controller
{
[HttpGet]
public ActionResult HandleForm()
{
var file = new XMLRecord()
{
Records = new List<XMLRecord>(){
new XMLRecord(){Type="Title", Contenu="Head of Service"},
new XMLRecord(){Type="Item", Contenu="Dr. A.Libois"}
}
};
return View(file);
}
[HttpPost]
public ActionResult HandleForm(XMLRecord file)
{
if (file == null)
{
return HttpNotFound();
}
else
{
return Content("It's OK");
}
}
}
In your partial view I changed the collection's name to Records instead of XMLRecords because the name of the collection in your model is Records.
<li style="padding-bottom:15px" >
#using (Html.BeginCollectionItem("Records")) {
<img src="#Url.Content("~/Content/images/draggable.jpg")" height="20"width="20" style="cursor: move" alt=""/>
#Html.LabelFor(model => model.Type)
#Html.EditorFor(model => model.Type)
#Html.LabelFor(model => model.Contenu)
#Html.EditorFor(model => model.Contenu)
Delete
}
Since your Model(XMLRecord) contains a member named Record, you have to use
#using (Html.BeginCollectionItem("Records"))
instead of
#using (Html.BeginCollectionItem("XmlRecords"))
If the problem still exists, take a look at similar problem mentioned in nested-begincollectionitem.
I have a Fairly Complex Form that I need to post to my MVC controller.
Here is the View model which I initially pass to the view on creation:
public class EditViewModel
{
public Service service { get; set; }
public bool sms { get; set; }
public bool email { get; set; }
public string userId { get; set; }
}
Here is my View (simplified):
#model IList<Service_Monitor_Web_Interface.Models.ViewModels.EditViewModel>
#{
ViewBag.Title = "Configure User Notifications";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.Title</h2>
#using (Html.BeginForm("Edit", "Users", FormMethod.Post, new { #class = "stdform stdform2", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
<p>
<label><u> Service:</u> </label>
<span class="field">
<u>Notification Methods:</u>
</span>
</p>
for (int i = 0; i < Model.Count; i++)
{
<p>
<label>#Model[i].service.Name</label>
<span class="field">
#Html.CheckBoxFor(model => model[i].sms)
SMS
#Html.CheckBoxFor(model => model[i].email)
Email
</span>
</p>
}
<br clear="all" /><br />
<p class="stdformbutton">
<button class="submit radius2">Save</button>
<input type="reset" class="reset radius2" value="Reset Form" />
</p>
}
And here is my Action method in my controller:
//
// POST: /Users/Edit
[HttpPost]
public ActionResult Edit(IList<EditViewModel> viewModel)
{
return View(viewModel);
}
How Can I bind my view model when receiving it on the controller?
Currently when I debug the action method receives a ViewModel which looks like so:
How can I get service and userId not to be null?
Note that in your helpers' lambdas, say in model => service.sms right part (service.sms) formally is not derived from the left part (model). That causes all name attributes of resulting inputs to be the same, and gives you request parameters that you did not expect.
The standard practice is to use for instaed of foreach in loop cases. That way name attributes for resulting html are generated correctly:
for(int i=0; i<Model.Count; i++)
{
<p>
<label>#Model[i].service.Name</label>
<span class="field">
#Html.CheckBoxFor(model => model[i].sms)
SMS
#Html.CheckBoxFor(model => model[i].email)
Email
</span>
</p>
}
Note that this requires Model to be of type implementing IList rather than IEnumerable.
Update. For other values, that do not have any UI for them, you can use hidden fields, so that they are not visible for the user and are nevertheless posted to the server:
<label>#Model[i].service.Name</label>
<span class="field">
#Html.CheckBoxFor(model => model[i].sms)
SMS
#Html.CheckBoxFor(model => model[i].email)
Email
#Html.HiddenFor(mode => model[i].userId)
#Html.HiddenFor(mode => model[i].service.Name)
...other field of service you want to be posted...
</span>
I'm rather new to the ASP.net MVC world and I'm trying to figure out how to render a group of checkboxes that are strongly typed to a view model. In webforms I would just use the checkboxlist control but im a bit lost with MVC.
I'm building a simple contact form for a wedding planning business and need to pass whatever checkbox values the user selects to my controller.
The form checkboxes need to look like this:
Your help would be greatly appreciated. Thanks!
Here's what I have so far.
CONTROLLER
[HttpPost]
public ActionResult Contact(ContactViewModel ContactVM)
{
if (!ModelState.IsValid)
{
return View(ContactVM);
}
else
{
//Send email logic
return RedirectToAction("ContactConfirm");
}
}
VIEW MODEL
public class ContactViewModel
{
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
public string Subject { get; set; }
public IEnumerable<SelectListItem> SubjectValues
{
get
{
return new[]
{
new SelectListItem { Value = "General Inquiry", Text = "General Inquiry" },
new SelectListItem { Value = "Full Wedding Package", Text = "Full Wedding Package" },
new SelectListItem { Value = "Day of Wedding", Text = "Day of Wedding" },
new SelectListItem { Value = "Hourly Consultation", Text = "Hourly Consultation" }
};
}
}
//Not sure what I should do for checkboxes...
}
VIEW
#model NBP.ViewModels.ContactViewModel
#{
ViewBag.Title = "Contact";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
<div id="ContactContainer">
<div><span class="RequiredField">* </span>Your Name:</div>
<div>
#Html.TextBoxFor(model => model.Name)
</div>
<div><span class="RequiredField">* </span>Your Phone:</div>
<div>
#Html.TextBoxFor(model => model.Phone)
</div>
<div><span class="RequiredField">* </span>Your Email:</div>
<div>
#Html.TextBoxFor(model => model.Email)
</div>
<div>Subject:</div>
<div>
#Html.DropDownListFor(model => model.Subject, Model.SubjectValues)
</div>
<div>Vendor Assistance:</div>
<div>
<!-- CHECKBOXES HERE -->
</div>
<div>
<input id="btnSubmit" type="submit" value="Submit" />
</div>
</div>
}
You could enrich your view model:
public class VendorAssistanceViewModel
{
public string Name { get; set; }
public bool Checked { get; set; }
}
public class ContactViewModel
{
public ContactViewModel()
{
VendorAssistances = new[]
{
new VendorAssistanceViewModel { Name = "DJ/BAND" },
new VendorAssistanceViewModel { Name = "Officiant" },
new VendorAssistanceViewModel { Name = "Florist" },
new VendorAssistanceViewModel { Name = "Photographer" },
new VendorAssistanceViewModel { Name = "Videographer" },
new VendorAssistanceViewModel { Name = "Transportation" },
}.ToList();
}
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
public string Subject { get; set; }
public IEnumerable<SelectListItem> SubjectValues
{
get
{
return new[]
{
new SelectListItem { Value = "General Inquiry", Text = "General Inquiry" },
new SelectListItem { Value = "Full Wedding Package", Text = "Full Wedding Package" },
new SelectListItem { Value = "Day of Wedding", Text = "Day of Wedding" },
new SelectListItem { Value = "Hourly Consultation", Text = "Hourly Consultation" }
};
}
}
public IList<VendorAssistanceViewModel> VendorAssistances { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new ContactViewModel());
}
[HttpPost]
public ActionResult Index(ContactViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
//Send email logic
return RedirectToAction("ContactConfirm");
}
}
View:
#using (Html.BeginForm())
{
<div id="ContactContainer">
<div><span class="RequiredField">* </span>Your Name:</div>
<div>
#Html.TextBoxFor(model => model.Name)
</div>
<div><span class="RequiredField">* </span>Your Phone:</div>
<div>
#Html.TextBoxFor(model => model.Phone)
</div>
<div><span class="RequiredField">* </span>Your Email:</div>
<div>
#Html.TextBoxFor(model => model.Email)
</div>
<div>Subject:</div>
<div>
#Html.DropDownListFor(model => model.Subject, Model.SubjectValues)
</div>
<div>Vendor Assistance:</div>
<div>
#for (int i = 0; i < Model.VendorAssistances.Count; i++)
{
<div>
#Html.HiddenFor(x => x.VendorAssistances[i].Name)
#Html.CheckBoxFor(x => x.VendorAssistances[i].Checked)
#Html.LabelFor(x => x.VendorAssistances[i].Checked, Model.VendorAssistances[i].Name)
</div>
}
</div>
<div>
<input id="btnSubmit" type="submit" value="Submit" />
</div>
</div>
}
Use a string array in your view model. You can then use the helper I hacked together. if you don't want to use the helper and the enum then see the actual Html at the bottom. The binder will return a string array with only the selected string values in it. if none are selected it returns a null value for your array. You must account for that, you have been warned :)
View Model:
[Display(Name = "Which Credit Cards are Accepted:")]
public string[] CreditCards { get; set; }
Helper:
public static HtmlString CheckboxGroup<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> propertySelector, Type EnumType)
{
var groupName = GetPropertyName(propertySelector);
var modelValues = ModelMetadata.FromLambdaExpression(propertySelector, htmlHelper.ViewData).Model;//propertySelector.Compile().Invoke(htmlHelper.ViewData.Model);
StringBuilder literal = new StringBuilder();
foreach (var value in Enum.GetValues(EnumType))
{
var svalue = value.ToString();
var builder = new TagBuilder("input");
builder.GenerateId(groupName);
builder.Attributes.Add("type", "checkbox");
builder.Attributes.Add("name", groupName);
builder.Attributes.Add("value", svalue);
var contextValues = HttpContext.Current.Request.Form.GetValues(groupName);
if ((contextValues != null && contextValues.Contains(svalue)) || (modelValues != null && modelValues.ToString().Contains(svalue)))
{
builder.Attributes.Add("checked", null);
}
literal.Append(String.Format("</br>{1} <span>{0}</span>", svalue.Replace('_', ' '),builder.ToString(TagRenderMode.Normal)));
}
return (HtmlString)htmlHelper.Raw(literal.ToString());
}
private static string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> propertySelector)
{
var body = propertySelector.Body.ToString();
var firstIndex = body.IndexOf('.') + 1;
return body.Substring(firstIndex);
}
HTML:
#Html.CheckboxGroup(m => m.CreditCards, typeof(VendorCertification.Enums.CreditCardTypes))
Use this if helper extensions scare you:
<input id="CreditCards" name="CreditCards" type="checkbox" value="Visa"
#(Model.CreditCards != null && Model.CreditCards.Contains("Visa") ? "checked=true" : string.Empty)/>
<span>Visa</span><br />
<input id="CreditCards" name="CreditCards" type="checkbox" value="MasterCard"
#(Model.CreditCards != null && Model.CreditCards.Contains("MasterCard") ? "checked=true" : string.Empty)/>
<span>MasterCard</span><br />
For me this works too, and I think this is the simplest (reading the previous answers).
The viewmodel has a string[] for the check boxes.
public string[] Set { get; set; }
The view has this code, and you can repeat the input as many times you need. name, id of the input control has to match the name of the property of the viewmodel.
<div class="col-md-3">
<div class="panel panel-default panel-srcbox">
<div class="panel-heading">
<h3 class="panel-title">Set</h3>
</div>
<div class="panel-body">
<div class="form-group-sm">
<label class="control-label col-xs-3">1</label>
<div class="col-sm-8">
<input type="checkbox" id="Set" name="Set" value="1" />
</div>
<label class="control-label col-xs-3">2</label>
<div class="col-sm-8">
<input type="checkbox" id="Set" name="Set" value="2" />
</div>
</div>
</div>
</div>
</div>
On the post method the Set variable is an array, having the checked value(s).