我是MVC的新手,也是編程新手(一般意義上的)。ASP.NET MVC 3.0 - 發佈MultiSelectList值到數據庫
我與如何發佈多個數據庫條目到我的數據庫基礎上,我從我已經填充的MultiSelectList拉動值的概念(通過我的控制器)掙扎。
基本上,我試圖創建一個包含州和城市的簡單模型,並允許用戶根據從單獨的靜態數據庫中提取的州/城市值來選擇並保存多個城市值到他們的帳戶。
這裏是我的模型:
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; }
}
}
這裏是我的查看數據的片段(包括多選列表的城市,我沒有問題填充):
<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>
這裏是我的創建/發佈控制器:
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);
}
正如你所看到的,我錯過了我的[HttpPost]低我保存多個值到db數據庫,但我不知道它到底是什麼缺少。我已經看到一些解釋這個在創建IEnumerable列表方面的帖子,但我想我只是不確定我需要這樣做,因爲我已經通過數據庫調用成功地填充了我的MultiSelectList。
任何幫助,非常感謝!
編輯:
基於下面的答案,如果我想創建基於我從MultiSelectList收集結果多新的數據庫行,我需要使用Form集合抓住這些結果和解析它們在我的HttpPost:
而且......我不知道該怎麼做。我認爲這些方針的東西:
[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);
}
沿上方,在這裏我創建基於我multiselectlist收集的東西線,它分成多個變量,並通過我的database.SaveChanges步驟多次我之前重定向?
謝謝!
你如何想象在單個城市變量中存儲多個城市? – archil 2012-07-14 15:59:31