0


MVC4 アプリケーションがあり、DropDownList のパラメーターをデータベースから取得していますが、DropDownList 値をデータベースにポストする際に何らかの問題が発生します。さまざまなアプローチのサンプルがたくさんありますが、Ajax、Javascript などの追加のアプローチを使用せずにメソッドを適用したいと考えています。一方、データを渡すために「FormCollection」に遭遇しましたが、よくわかりませんこのシーンで FormCollection が最適な方法である場合。私が使用するビュー、コントローラー、モデルの一部を次に示します。

意見:

@using (Html.BeginForm("Add", "Product", FormMethod.Post,
    new { enctype = "multipart/form-data" }))
{    
    <p>Product Type : @Html.DropDownListFor(m => m.SelectedLookupId, new SelectList(Model.Lookups.Where(x => x.LookupType == "Product Type"), "LookupID", "LookupValue"), "--- Select ---") </p>


コントローラ:

[HttpPost]
    public ActionResult Add(Product product)
    {
        if (ModelState.IsValid)
        {
            product.ProductType = // ??? Cannot get the SelectedLookupId
            ...
            repository.SaveProduct (product);
            TempData["message"] = string.Format("{0} has been saved", product.Name);
            return View("Completed");
        }
        else
        {
            //there is something wrong with the data values
            return View(product);
        }
    }


ビューモデル:

public class ProductViewModel
{
    public IEnumerable<Product> Products { get; set; }
    public IEnumerable<Lookup> Lookups { get; set; } //Lookup for Product Types
    public int SelectedLookupId { get; set; }

    public Product Product { get; set; }
}


ご協力いただきありがとうございます。


4

2 に答える 2

0

返信ありがとうございます。実際、View ではなく ViewModel を使用することで、問題を解決できました。一方、いくつかの調査の後、ViewModel を必要とせずに Dropdownlist を設定するために、別の効果的な方法を適用しました。さらに、この例では、以下に示すように、同じルックアップ テーブルで複数の外部キーを使用できます。これは、3 つの外部キーを持つ申請者エンティティと、これらのキーに関連するルックアップエンティティです。この例で達成したかったのは、いくつかのパラメーター (これらのパラメーターはLookupTypeルックアップ テーブルのプロパティ)。以下に完全な例を示します (簡潔にするために関連のないプロパティを省略しています)。

申請者エンティティ:

public class Applicant
{
    [Key]
    public int ApplicantID { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }

    // for using "Multiple foreign keys within same table using Fluent API"
    public int? HasDoneAnyProject { get; set; }
    public int? IsInterestedAnyProgramme { get; set; }
    public int? InterestedProgrammeId { get; set; }

    public virtual Lookup PrimaryLookup { get; set; }
    public virtual Lookup SecondaryLookup { get; set; }
    public virtual Lookup TertiaryLookup { get; set; }

}


検索エンティティ:

public class Lookup
{
    [Key]
    public int LookupID { get; set; }
    public string LookupType { get; set; }
    public string LookupValue { get; set; }

    // for using "Multiple foreign keys within same table using Fluent API" 
    public virtual ICollection<Applicant> PrimaryLookupFor { get; set; }
    public virtual ICollection<Applicant> SecondaryLookupFor { get; set; }
    public virtual ICollection<Applicant> TertiaryLookupFor { get; set; }     
} 


Dbコンテキスト:

public class EFDbContext : DbContext
{
    public DbSet<Applicant> Applicants { get; set; }
    public DbSet<Lookup> Lookups { get; set; }

    //for using "Multiple foreign keys within same table using Fluent API"
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Applicant>()
                .HasOptional(b => b.PrimaryLookup)
                .WithMany(a => a.PrimaryLookupFor)
                .HasForeignKey(b => b.HasDoneAnyProject)
                .WillCascadeOnDelete(false); 

        modelBuilder.Entity<Applicant>()
                .HasOptional(b => b.SecondaryLookup)
                .WithMany(a => a.SecondaryLookupFor)
                .HasForeignKey(b => b.IsInterestedAnyProgramme)
                .WillCascadeOnDelete(false);

        modelBuilder.Entity<Applicant>()
                .HasOptional(b => b.TertiaryLookup)
                .WithMany(a => a.TertiaryLookupFor)
                .HasForeignKey(b => b.InterestedProgrammeId)
                .WillCascadeOnDelete(false);
    }
}


コントローラ:

private void PopulateLookupsDropDownList(string lookupType, string foreignKey, object selectedLookups = null)
{
    var lookupsQuery = repository.Lookups
   .Select(x => x)
   .Where(x => x.LookupType == lookupType)
   .OrderBy(x => x.ParentLookupID).ToList();
    ViewData[foreignKey] = new SelectList(lookupsQuery, "LookupID", "LookupValue", selectedLookups);
}

3 つのドロップダウンリストのそれぞれに対してメソッドを呼び出す場合:

PopulateLookupsDropDownList("YesNo", "HasDoneAnyProject", applicant.HasDoneAnyProject);
PopulateLookupsDropDownList("YesNo", "IsInterestedAnyProgramme", applicant.IsInterestedAnyProgramme);
PopulateLookupsDropDownList("Programme", "InterestedProgrammeId", applicant.InterestedProgrammeId);


View: : 異なる LookupType パラメーターを使用して、同じルックアップ テーブルから 3 つのドロップダウン リストのそれぞれを入力します。

<label>Has done any project before?</label>
@Html.DropDownList("HasDoneAnyProject", "---- Select ----")

<label>Are you interested in any programme?</label>
@Html.DropDownList("IsInterestedAnyProgramme", "---- Select ----")

<label>Interested programme name?</label>
@Html.DropDownList("InterestedProgrammeId", "---- Select ----")


このアプローチが、同じルックアップ テーブルからドロップダウン リストを作成したい人にとって役立つことを願っています。一方、これに適しているだけでなく、さまざまなテーブルからドロップダウンリストを作成するためにも使用できます。
よろしく。

于 2013-10-18T22:02:57.313 に答える
0

次のように、アクション メソッドは、製品自体ではなく、ビュー モデルを受け取る必要があります。

[HttpPost]
public ActionResult Add(ProductViewModel productViewModel)

私が混乱していない限り。しかし、あなたが上に投稿したビューのスニペットは Add ビューからのものであり、そのビューのモデルのタイプはProductViewModel. アクション メソッドでは、モデルの状態が無効な場合に Add ビューを返していますが、Productそのビューに a を渡しています。タイプが一致しないという実行時エラーが発生するため、ここでも混乱する可能性があります。

于 2013-08-17T19:42:38.183 に答える