0

これが私がやろうとしていることです:

MultiSelectList から複数の文字列値を収集しようとしています。HttpPost で、関連付けられたモデルのその MultiSelectList の各値に対応する新しい個別のデータベース行を作成します。

この場合、Service Location のデータベース エントリを作成しようとしています (たとえば、ロサンゼルス、サン ディエゴ、およびサンフランシスコでサービスを提供する配管工)。そのため、彼は私のアプリケーションに移動し、State: California を選択してから、City: Los Angeles、San Diego、San Francisco を選択します。これにより、それぞれに新しい SPServiceLocationID を持つ 3 つの新しいレコードが作成されます。

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 を変更して複数の全体を作成する方法について、誰かが私のためにチュートリアルを参照したり、支援を提供したりできる場合は?

私の知識は非常に基本的なものなので、どんな助けでも大歓迎です!

4

1 に答える 1

0

ここに役立つはずのチュートリアルがあります:

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

また、ViewBag の使用をやめ、ViewModel を使用して情報を処理することを検討する必要があります (これにより、作業がずっと楽になります)。

ViewModel のベスト プラクティス

于 2012-07-16T14:29:22.693 に答える