I have a model, MyModel, with a list property and an accompanying string used to store the values in the database.
Simplifying a bit to increase readability.
public class MyModel
{
public int ID { get; set; }
public List<int> Numbers { get; set; }
[Column, ScaffoldColumn(false)]
public string NumbersStore { get { /*parses Numbers*/ } set { /*splits the value and sets Numbers accordingly*/ } }
}
I'm using basic CRUD, based off the scaffolding.
In my Create
/Edit
views, I have manually written a select multiple
. Not using helpers was probably a bad idea. I have no problem retrieving these values in the Index
, Details
, and Delete
views, but I cannot figure out how to actually bind this data to my model when creating/editing.
Just from some blind Googling, I've tried:
- Added a list to the MyModelController.Create parameters list
- Attempted to use Request.Form["SelectNameAttribute"]
CSHTML:
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(model => model.Numbers, htmlAttributes: new { @class = "control-label col-md-2" })
<select class="select2 col-md-10 form-control" multiple="multiple" id="Numbers" name="Numbers">
<!-- Ultimately enumerated with a loop that goes through the database, probably butchering MVC conventions. Don't think that's relevant to the question. -->
<option value="1">One</option>
<option value="2">Two</option>
<!-- Etc. -->
</select>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
Controller:
public ActionResult Create([Bind(Include = "ID,NumbersStore")] MyModel myModel) // Changing NumbersStore to Numbers does nothing
{
//myModel.NumbersStore = Request.Form["Numbers"].ToString();
if (ModelState.IsValid)
{
db.MyModels.Add(myModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(myModel);
}