0
我有一個應用程序在Asp.NET MVC與實體數據模型。現在我有一個state_master表的模型,其中只有一個屬性'State_Name',並且在數據庫表中,我有兩個字段'State_ID',它是自動遞增的,'State_Name'將爲其插入數據。 現在,因爲我在模型中只有一個屬性,所以我無法使用此模型獲取字段'State_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");
}
}
}
爲什麼不在模型中保留state_Id?沒有那個你怎麼能綁定數據? –
因爲我的state_id在數據庫字段處自動遞增,當我插入數據時會拋出錯誤。 –
你在使用實體框架嗎? EF提供了將ID列映射到由數據庫處理的值生成。插入新實體時,不需要設置ID。您只需設置Id屬性以外的其他屬性值。 –