2017-03-31 53 views
0

我有一個應用程序在Asp.NET MVC與實體數據模型。現在我有一個state_master表的模型,其中只有一個屬性'State_Name',並且在數據庫表中,我有兩個字段'Sta​​te_ID',它是自動遞增的,'State_Name'將爲其插入數據。 現在,因爲我在模型中只有一個屬性,所以我無法使用此模型獲取字段'Sta​​te_ID'和'State_Name'。這是我面臨的問題。如何在Asp.NET MVC中獲取所有字段的表單數據庫?

國家示範性文件:

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Web; 

namespace ViewData.Models 
{ 
public class state_model 
     { 
     [Key] 
     public string state_name { get; set; } 
     } 
} 

查看文件:

@using ViewData.Models 
@{ 
    Layout = null; 
} 

    <!DOCTYPE html> 
    <html> 
    <head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>state_view</title> 
    </head> 
    <body> 
    <div> 
    <ul> 
     @foreach (var state in ViewData["states"] as IList<state_model>) 
      { 
      <li> 
       @state.state_name 
      </li> 
      } 
    </ul> 
    </div> 
    </body> 
    </html> 

控制器的文件:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using ViewData.DataAccessLayer; 
using ViewData.Models; 
namespace ViewData.Controllers 
{ 
public class StateController : Controller 
    { 
    // GET: State 
    public ActionResult Index() 
     { 
     DataLayer dl = new DataLayer(); 
     IList<state_model> data = (from o in dl.states select o).ToList(); 
     ViewData["states"] = data; 
     return View("state_view"); 
     } 
    } 
} 
+0

爲什麼不在模型中保留state_Id?沒有那個你怎麼能綁定數據? –

+0

因爲我的state_id在數據庫字段處自動遞增,當我插入數據時會拋出錯誤。 –

+1

你在使用實體框架嗎? EF提供了將ID列映射到由數據庫處理的值生成。插入新實體時,不需要設置ID。您只需設置Id屬性以外的其他屬性值。 –

回答

0

你需要創建一個視圖模型爲國家獲取和綁定數據庫中的所有字段。例如,

public class state_ViewModel 
    { 
    [Key] 
    public int state_Id { get; set; } //check with your data type 
    public string state_name { get; set; } 
    } 

所以在你的控制器方法中,你可以使用這個來獲取和綁定。而對於插入記錄可以使用state_model

,並在你的操作方法,

public ActionResult Index() 
    { 
    DataLayer dl = new DataLayer(); 
    IList<state_ViewModel> data = (from o in dl.states select o).ToList(); 
    ViewData["states"] = data; 
    return View("state_view"); 
    } 

見,視圖模型是什麼,但在視圖渲染數據。 要了解更多關於視圖模型的信息,請單擊here

相關問題