2016-12-14 104 views
0

我是MVC的初學者(但不是在C#中),但項目必須使用實體框架在Visual Studio .NET應用程序(MVC或WPF)中製作。我做了一個數據庫的第一個應用,但這裏是我的問題:MVC組合框以及如何將其保存在數據庫中?

在Customers表
我有ID,標題,名稱,中間名,姓,地址,CountryId(關係表的國家[ID,名稱] 1對多),活動(位,真/假,多選)

在表國家
ID,姓名(預定)

另一個表標題(即我做了,因爲我不能硬編碼dropdownlists)
標識,標題名稱

我的問題是當我創建Controller + View時,標題顯示爲TextBox(aka @ Html.Editor(...)),當我將其更改爲@Html.DropDownList("nameHere", null, new { htmlAttributes = new { @class = "form-control" } })

然後在我的GET中創建下拉視圖清單:

public ActionResult Create() 
     { 
      ViewBag.nameHere = new SelectList(db.Titles, "Id", "TitleName"); 
      ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name"); 
      return View(); 
     } 

然後在我的文章中,我把它太:

[HttpPost] 
     [ValidateAntiForgeryToken] 
     public ActionResult Create([Bind(Include = "Id,Title,Name,MiddleName,Surname,Address,CountryId,Active")] Customer customer) 
     { 
      if (ModelState.IsValid) 
      { 
       db.Customers.Add(customer); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 
      ViewBag.nameHere = new SelectList(db.Titles, "Id", "TitleName", db.Title); //selects from table Titles the Id and TitleName for the field Title in Customers table? at least that's how I interpretate it 
      ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name", customer.CountryId); //same for Country 
      return View(customer); 
     } 

但我有3個問題:

一日一 - 在db.Customersñ名稱服務器返回ULL值
第二個 - 如果我不使用下拉,那麼它會從TextBox字段發送值(但人們可以寫任何他們想要的)
第三個(當使用ViewBag和ViewData時) - 沒有ViewData項目類型'IEnumerable'有關鍵字'nameHere'

我只想要一個簡單的下拉列表,我有4個選項 - 女士,夫人,先生,小姐,當我選擇它併發送完整的表單到服務器名稱,中間名,姓氏等),在Customers表中保存下拉列表中的字符串。而已。

我做我的數據庫優先(又名創建數據庫,然後示範,而不是相反)分貝

+0

每個帖子問一個問題,不要問一堆問題 –

+0

我問如何使視圖中的下拉列表選項(可以說它顯示「先生」)保存在我的數據庫在標題(類型串)。它發送一個空值! –

+0

你是如何閱讀它的後行動,顯示特定代碼 –

回答

0

我設法想出一些OOP的答案:

Inside the controller(GET method): 
List<string> ListItems = new List<string>(); 
      ListItems.Add("Ms."); 
      ListItems.Add("Mrs."); 
      ListItems.Add("Mr."); 
      ListItems.Add("Miss"); 
      SelectList Titles = new SelectList(ListItems); 
      ViewData["Titles"] = Titles; 

裏面的景觀:

<div class="form-group"> 
      @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.DropDownList("Title", ViewData["Titles"] as SelectList, new { @class = "form-control" }) 
       @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
相關問題