2013-08-17 1 views
0


MVC4 응용 프로그램이 있고 데이터베이스에서 DropDownList에 대한 매개 변수를 가져 왔지만 DropDownList 값을 데이터베이스에 게시하는 동안 몇 가지 문제가 발생했습니다. 다른 접근 방식에 대한 샘플이 많이 있지만 Ajax, Javascript 등의 추가 접근 방식을 사용하지 않고 메소드를 적용하고 싶습니다. 반면에 "FormCollection"을 실행하여 데이터를 전달했지만 확실하지 않습니다. FormCollection이이 장면에서 가장 좋은 방법 인 경우.MVC4에서보기에서 DropDownList 값을 컨트롤러로 게시

보기 :

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


주셔서 감사합니다 도움을 위해.


+0

'문제가 발생하지 않았습니다 ...'product.SelectedLookupId'의 문제점은 무엇입니까? – AminSaghi

답변

0

답장을 보내 주셔서 감사합니다. 실제로 View가 아닌 ​​ViewModel을 사용하여 문제를 해결할 수있었습니다. 다른 한편으로, 일부 연구 후에 ViewModel을 사용하지 않고도 Dropdownlist를 채우기 위해 다른 효과적인 방법을 적용했습니다. 또한이 예제를 사용하면 아래와 같이 동일한 조회 테이블에서 여러 개의 외래 키를 사용할 수 있습니다. 신청자 3 개의 외래 키와 Lookup 이러한 키와 관련된 엔티티가 있습니다. 이 예제를 사용하여 달성하고자하는 것은 정확히 여러 Dropdownlist 매개 변수 즉, 성별, 예/아니요, 상태 등에 대한 조회 테이블을 사용하는 것입니다. 여러 매개 변수에 대한 테이블을 만들 필요가 없으므로 이러한 매개 변수는 구분됩니다 (이 매개 변수는 구별됩니다) 찾아보기 테이블의 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; }  
} 


DbContext :

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

세 DropDownList로 각각의 방법을 호출하기위한 :

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


보기 : :

<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 ----") 
: 다른 LookupType 매개 변수와 같은 조회 테이블에서 세 개의 드롭 다운리스트의 각을 채우기


이 접근 방식이 유용하게 사용되기를 바랍니다. 드롭 다운 목록을 동일한 조회 테이블에서 채우려는 사람들을위한 것입니다. 다른 한편으로는, 이것에 적합 할뿐만 아니라, 다른 테이블의 드롭 다운리스트를 채우는데도 사용할 수 있습니다.
감사합니다.

0

액션 방법과 같이, 아닌 제품 자체 뷰 모델을 수신해야합니다

[HttpPost] 
public ActionResult Add(ProductViewModel productViewModel) 

내가 혼란 스러워요하지 않는 한. 하지만 위의 게시 스 니펫이 추가보기에 있고 해당보기의 모델이 ProductViewModel 인 것으로 가정합니다. 액션 메서드에서 모델 상태가 유효하지 않을 때 Add 뷰를 반환하지만 Product을 해당 뷰에 전달합니다. 다시 말해서 유형이 일치하지 않는 런타임 오류가 발생하므로 혼동 될 수 있습니다.

+1

답장을 보내 주셔서 감사합니다. 사실이 스레드를 만들기 전에 ** ProductViewModel ** 및 ** Product **을 모두 사용하려고 시도했으며 다음 결과에서 얻은 결과는 다음과 같습니다. a) ** ProductViewModel **, ** productViewModel **. Product 속성 null를 돌려줍니다. b) 제품을 사용할 때 당연히 데이터베이스에 쓰는 데 필요한 ** SelectedLookupId ** 속성을 얻을 수 없습니다. 그래서, 데이터베이스에서 조회 값을 얻는 Dropdownlist 등의 입력 요소를 사용할 때 어떤 접근 방식을 따라야하는지 궁금했습니다. 문안 인사. –

+0

'ProductViewModel' 또는'Product' 두 경우 모두 요청에서받는 정보 즉, 경로 값, 쿼리 문자열 값 및 양식 값을 기반으로 모델 바인딩을 통해 개체가 수화 될 수 있습니다. 'ProductViewModel'을 사용한 경우,'Product' 속성은 당신이 그것을 채우라는 요구로부터 아무 것도 없기 때문에 null 일 가능성이 높습니다. – asymptoticFault

관련 문제