2011-01-31 3 views
1

두 모델로 구성된 매우 간단한 데이터 구조가 있습니다. 첫 번째 테이블에는 UserName, UserQuestion 및 userLocationID가 있고 다른 테이블에는 LocationName 및 LocationID가 있으며 첫 번째 테이블의 locationID는 두 번째 테이블의 LocationName과 관련이 있습니다. 그러나 나는 어떤 관계도 지정하지 않았다. 코드의 첫 번째 방법 인 here을 사용하여 데이터 구조를 설정했습니다.MVC3에서 관련 ID를 사용하여 양식에 선택 상자 채우기

사용자가 이름과 질문을 입력 할 수있는 두 개의 텍스트 입력과 두 번째 테이블의 모든 위치 이름이 채워진 선택 상자가있는 양식을 만들고 싶습니다. 그러나 나는 그렇게 할 수있는 모델을 만들 수없는 것 같습니다. 별도의 ViewModel을 만들어야합니까?

누구든지이 작업을 수행하는 방법을 설명하는 간단한 자습서를 알고 있습니까?

저는 MVC와 닷넷 프레임 워크에서 상당히 새로 왔습니다. . 그리고 나는 this answer을 보았습니다.하지만 제 필요에 맞게 수정할 수없는 것 같습니다. 그래서 사과하면 정말 기본적인 것을 묻습니다.

답변

0

하나의 컨트롤러, 하나의보기 및 3 개의 C# 클래스에서 예제를 제공 할 수 있습니다. 이 코드를 사용하려면 Visual Studio에서 빈 MVC2 프로젝트를 만들고 Entity Framework dll 버전 4.1에 대한 참조를 추가하십시오. 이 파일들을 어디에 넣어야하는지에 관해 도움이 필요하면 나는 Steve Sanderson's MVC2 book을 추천한다.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<User>" %> 

<html> 
<body> 
    <% using (Html.BeginForm()) 
     {%> 
    Username: <%: Html.TextBoxFor(model => model.UserName) %><br /> 
    Question: <%: Html.TextBoxFor(model => model.Question) %><br /> 
    Location: <select name="categoryId"> 
     <% foreach (var location in new Repository().GetLocations()) 
      {%> 
     <option value="<%= location.ID %>"> 
      <%= location.LocationName %></option> 
     <%} %> 
    <br /> 
    </select> 
    <p> 
     <input type="submit" value="Create" /> 
    </p> 
    <% } %> 
</body> 
</html> 
홈 \ Index.aspx \

using System.Web.Mvc; 

public class HomeController : Controller 
{ 
    Repository repo = new Repository(); 

    [HttpGet] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(User user, int categoryId) 
    { 
     user.Category = repo.GetLocation(categoryId); 
     repo.SaveUser(user); 
     return View(); 
    } 
} 

조회수 :

public class User 
{ 
    public int ID { get; set; } 
    public string UserName { get; set; } 
    public string Question { get; set; } 

    public virtual Location Category { get; set; } 
} 

public class Location 
{ 
    public int ID { get; set; } 
    public string LocationName { get; set; } 
} 

저장소

using System.Data.Entity; 
using System.Collections.Generic; 
using System.Linq; 

public class Repository : System.Data.Entity.DbContext 
{ 
    public DbSet<User> User { get; set; } 
    public DbSet<Location> Locations { get; set; } 

    public Repository() 
    { 
     this.Database.Connection.ConnectionString = 
      @"Server=.;Database=Test;Integrated Security=SSPI"; 

     if (!this.Database.Exists()) 
     { 
      this.Database.Create(); 
      this.Locations.Add(new Location { LocationName = "Queensway" }); 
      this.Locations.Add(new Location { LocationName = "Shepherds Bush" }); 
      this.SaveChanges(); 
     } 
    } 

    public IEnumerable<Location> GetLocations() 
    { 
     return this.Locations.Where(x => x.ID > -1); 
    } 

    public Location GetLocation(int id) 
    { 
     return this.Locations.First(x => x.ID == id); 
    } 

    public void SaveUser(User user) 
    { 
     this.User.Add(user); 
     this.SaveChanges(); 
    } 
} 

컨트롤러 HomeContoller.cs을 \