简体   繁体   中英

ASP.NET MVC 3.0 - Issue posting MultiSelectList values to database

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM