1

I'm new to MVC and new to programming (in a general sense) as well.

I'm struggling with the concept of how to post multiple database entries into my database (via my controller) based on values I'm pulling from a MultiSelectList that I've populated.

Basically, I'm trying to create a simple model that contains a State and a City, and lets the user select and save multiple City values to their account based on State/City values pulled from a separate, static database.

Here's 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 a snippet of my View data (including the multi-select list for city that I have no trouble populating):

<div class="editor-label">
        @Html.LabelFor(model => model.state)
    </div>
    <div class="editor-field">
        @Html.DropDownList("state", ViewBag.state as SelectList, "Select a state...",    new { @class = "chzn-select", onchange = "CityChange()" })
        @Html.ValidationMessageFor(model => model.state)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.city)
    </div>

    <div class="editor-field" id="SP_SelectCity">
        @Html.ListBox("city", ViewBag.city as MultiSelectList, new { @class = "chzn-select", data_placeholder = "Select cities..." })
        @Html.ValidationMessageFor(model => model.city)
    </div>

    <p>
        <input type="submit" value="Submit" />
    </p>

And here are my Create/Post Controllers:

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();
    } 

    [HttpPost]
    public ActionResult Create(SPServiceLocation spservicelocation, FormCollection formValues)
    {

            if (ModelState.IsValid)
            {

                db.SPServiceLocation.Add(spservicelocation);
                db.SaveChanges();
                return RedirectToAction("Create", "SPServiceLocation");
        }

        return View(spservicelocation);
    }

As you can see, I'm missing something in my [HttpPost] that'll allow me to save multiple values to the db database, but I'm not sure what exactly it is that's missing. I've seen some posts that explain this in terms of creating an IEnumerable list, but I guess I'm just not sure I need to do that since I'm already successfully populating my MultiSelectList via a database call.

Any help is greatly appreciated!

EDIT:

Based on the answers below, if I want to create multiple new database rows based on the results I collect from a MultiSelectList, I need to use Form collection to grab those results and parse them within my HttpPost:

And... I do not know how to do that. I assume something along these lines:

[HttpPost]
public ActionResult Create(SPServiceLocation spservicelocation, FormCollection formValues)
{

        if (ModelState.IsValid)
        {
            foreach (var item in x)
            {
            db.SPServiceLocation.Add(spservicelocation);
            db.SaveChanges();
            }
            return RedirectToAction("Create", "SPServiceLocation");
    }

    return View(spservicelocation);
}

Something along the lines of the above, where I create a collection based on my multiselectlist, break it into multiple variables, and step through my database.SaveChanges multiple times before I redirect?

Thanks!

Roban Kearby
  • 43
  • 1
  • 7

2 Answers2

0

The trick has nothing to do with your MVC code. You have to change either your Business Layer or Data Access Layer (DAL) code to read/write to 2 different databases.

I did the same project to answer one question sometime ago. Here it is: https://stackoverflow.com/a/7667172/538387

I checked the code, It's still working, you can download it and check it yourself.

Community
  • 1
  • 1
Tohid
  • 6,175
  • 7
  • 51
  • 80
  • Thanks Tohid, but I should clarify, I'm able to successfully read from the static database and write/save to my app's database, I'm just not able to do so for multiple values at once. In this case, the code above is creating a new record in my database, but only that one record for the first city I select (and ignoring selections two through three, four, five). What I want to be able to do is create a single record for each selected city that sits in the MultiSelectList. – Roban Kearby Jul 14 '12 at 16:28
  • Ok. Got it, I'll answer you in a new post. – Tohid Jul 14 '12 at 22:07
0

When user submits the Create forms and application flows to [HttpPost] public ActionResult Create action, all of the form data live in formValues parameter.

You have to read those data from formValues (like: formValues["companyID"], build appropriate model object from them, and then update the db.

Tohid
  • 6,175
  • 7
  • 51
  • 80
  • Thanks Tohid! This is exactly the path I'm attempting to take, any thoughts on how I would structure this for a MultiSelectList? – Roban Kearby Jul 16 '12 at 04:59
  • `@Html.DropDownList()`, `@Html.ListBox()` and any Html Helper that builds form element, has a given "name". So inside `[HttpPost]` method you can retrieve data by using their names; In your case: `formValues["state"]` and `formValues["city"]`. – Tohid Jul 17 '12 at 23:09