【问题标题】:ASP.NET MVC 3 - FormCollection for a MultiSelectListASP.NET MVC 3 - MultiSelectList 的 FormCollection
【发布时间】:2012-07-16 22:29:22
【问题描述】:

这是我想要做的:

我正在尝试从 MultiSelectList 收集多个字符串值,并在 HttpPost 上创建一个新的、单独的数据库行,对应于关联模型的 MultiSelectList 中的每个值。

在本例中,我尝试为服务位置创建数据库条目(例如,在洛杉矶、圣地亚哥和旧金山提供服务的管道工)。所以他会进入我的应用程序并选择州:加利福尼亚,然后选择城市:洛杉矶、圣地亚哥、旧金山……这将创建三个新记录,每个记录都有一个新的 SPServiceLocationID:

SPServiceLocationID:1 SPCompanyAccountID:4 状态:3 城市:洛杉矶

这是我的模型:

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

这是我用于生成视图的控制器,在这里填充我的 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();
}

这是生成 MultiSelectList 的查看代码:

@Html.ListBox("city", ViewBag.city as MultiSelectList, new { @class = "chzn-select", data_placeholder = "Select cities..." })

最后,这是我用于发布到数据库的控制器数据,这是我认为我需要帮助的部分:

[HttpPost]
public ActionResult Create(SPServiceLocation spservicelocation, FormCollection formValues)
{
    if (ModelState.IsValid)
    {

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

return View(spservicelocation);

}

如果有人可以为我参考一个教程,或者提供一些帮助,关于我如何在这种情况下处理 FormCollection 并修改我上面的 HttpPost 以便它创建多个整体?

我的知识非常基础,感谢任何帮助!

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 razor


    【解决方案1】:

    这是一个应该有帮助的教程:

    http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

    您应该考虑放弃使用 ViewBag 并转而使用 ViewModel 来处理您的信息(这将使您的生活更轻松):

    ViewModel Best Practices

    【讨论】:

      猜你喜欢
      • 2011-05-20
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多