Here’s what I’m trying to do:
I’m attempting to collect multiple string values from a MultiSelectList, and upon HttpPost, create a new, separate database row corresponding to each value in that MultiSelectList for the associated Model.
In this case, I’m trying to create database entries for Service Location (for example, a plumber who services in Los Angeles, San Diego, and San Francisco). So he would go into my application and select State: California and then City: Los Angeles, San Diego, San Francisco… which would create three new records, each with a new SPServiceLocationID:
SPServiceLocationID: 1 SPCompanyAccountID: 4 State: 3 City: Los Angeles
Here is my model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace BidFetcher.Models
{
public class SPServiceLocation
{
public int SPServiceLocationID { get; set; }
public int SPCompanyAccountID { get; set; }
[Display(Name = "State")]
public string state { get; set; }
[Required]
[Display(Name = "Cities (select all that apply)")]
public string city { get; set; }
public virtual SPCompanyAccount SPCompanyAccount { get; set; }
}
}
Here is my Controller for generating the View, where I have no issue populating my MultiSelectList:
public ActionResult Create()
{
ViewBag.sessionName = HttpContext.Session["SPCompanyName"].ToString();
var compID = HttpContext.Session["SPCompanyAccountID"].ToString();
ViewBag.companyID = compID;
ViewBag.state = new SelectList(simpleDB.simpleState, "simpleStateID", "simpleStateID");
ViewBag.city = new MultiSelectList(simpleDB.simpleCity, "cityFull", "cityFull");
return View();
}
Here is my View code that generates the MultiSelectList:
@Html.ListBox("city", ViewBag.city as MultiSelectList, new { @class = "chzn-select", data_placeholder = "Select cities..." })
And finally, here is my Controller data for posting to the database, which is the piece that I believe I need help:
[HttpPost]
public ActionResult Create(SPServiceLocation spservicelocation, FormCollection formValues)
{
if (ModelState.IsValid)
{
db.SPServiceLocation.Add(spservicelocation);
db.SaveChanges();
return RedirectToAction("Create", "SPServiceLocation");
}
return View(spservicelocation);
}
If someone can reference a tutorial for me, or provide some assistance, on how I might handle FormCollection in this scenario and modify my above HttpPost so that it’ll create multiple entires?
My knowledge s very basic, so any help is appreciated!