Created
March 28, 2013 08:16
-
-
Save jerone/5261556 to your computer and use it in GitHub Desktop.
CheckBox List in MVC C# ASP.NET
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// GET: /Brokers/Edit/5 | |
public ActionResult Edit(Guid id) | |
{ | |
Broker broker = db.Brokers.Find(id); | |
if (broker == null) | |
{ | |
return HttpNotFound(); | |
} | |
ViewBag.BrokerValues = GetBrokerValues(broker); | |
return View(broker); | |
} | |
// POST: /Brokers/Edit/5 | |
[HttpPost] | |
[ValidateAntiForgeryToken] | |
public ActionResult Edit(Broker broker, String[] brokerValue) | |
{ | |
if (ModelState.IsValid) | |
{ | |
Broker brokerToUpdate = db.Brokers.Find(broker.Id); | |
SetBrokerValues(brokerToUpdate, brokerValue); | |
db.Entry(brokerToUpdate).CurrentValues.SetValues(broker); | |
db.SaveChanges(); | |
return RedirectToAction("Index"); | |
} | |
return View(broker); | |
} | |
private List<BrokerValue> GetBrokerValues(Broker broker) | |
{ | |
List<RealEstateProperty> propertyValues = db.PropertyValues.ToList(); | |
var brokerValues = new List<BrokerValue>(); | |
foreach (var propVal in propertyValues) | |
{ | |
brokerValues.Add(new BrokerValue { Id = propVal.Id, Title = propVal.Value, Checked = broker.Values.Contains(propVal) }); | |
} | |
return brokerValues; | |
} | |
private void SetBrokerValues(Broker broker, String[] brokerValues) | |
{ | |
if (brokerValues == null) | |
{ | |
broker.Values.Clear(); | |
return; | |
} | |
IEnumerable<RealEstateProperty> propertyValues = db.PropertyValues; | |
broker.Values = propertyValues.Where(propVal => brokerValues.Contains(propVal.Id.ToString())).ToList(); | |
} | |
public class BrokerValue | |
{ | |
public Guid Id { get; set; } | |
public string Title { get; set; } | |
public bool Checked { get; set; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% foreach (BrokerValue brokerValue in ViewBag.BrokerValues) { %> | |
<input type="checkbox" name="brokerValue" value="<%: brokerValue.Id %>" id="brokerValue_<%: brokerValue.Id %>" <%: (Html.Raw(brokerValue.Checked ? "checked=\"checked\"" : "")) %> /> | |
<%-- Html.CheckBox("brokerValue", brokerValue.Checked, new { id = "brokerValue_" + brokerValue.Id }) --%> | |
<%: Html.Label("brokerValue_" + brokerValue.Id, brokerValue.Title) %> | |
<% } %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment