我正在嘗試學習 ASP.NET MVC 和 ADO.NET。我正在制作一個演示網站,其中會有一個管理面板。管理員將更新將反映在主頁上的每日訊息。我正在使用 ASP.NET MVC。我在資料庫中創建了表
create table DailyMsg
(
Sno int primary key,
msg varchar(max)
);
這是我的日常訪問層
public class DailyMsgs
{
static string connectionString = @"data source = DELL\SQLEXPRESS01;initial catalog = amen; persist security info=True;Integrated Security = SSPI;";
SqlConnection con = new SqlConnection(connectionString);
DailyMsg dm = new DailyMsg();
public string ViewDailyMessage()
{
SqlCommand com = new SqlCommand("sp_viewDsilyMSg", con);
com.CommandType = CommandType.StoredProcedure;
con.Open();
string simpleValue = com.ExecuteScalar().ToString();
con.Close();
return simpleValue;
}
}
我的模型課:
public partial class DailyMsg
{
public int Sno { get; set; }
public string msg { get; set; }
}
現在,我被困在這一步。我不知道如何將此回傳值放置simpleValue到<h2>我的視圖的標簽中。
我的控制器
DailyMsgs dailyMsgs = new DailyMsgs();
private amenEntities db = new amenEntities();
// GET: DailyMsgs
public ActionResult Index()
{
return View();
}
我的主頁:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
uj5u.com熱心網友回復:
不要將 Web 表單與 MVC 一起使用,而是使用視圖。
創建一個
Index.cshtml在Views/Home目錄中呼叫的視圖。或者使用簡單的方法 - 只需右鍵單擊Index()控制器中的操作并選擇Add View...在索引視圖的頂部添加
@model @<YourProjectName>.<Models>.DailyMsg并替換
<YourProjectName>.<Models>為DailyMsg類所在的實際命名空間當前,
dailyMsgs.ViewDailyMessage()回傳一個字串。您需要將其轉換為您的模型:// GET: DailyMsgs public ActionResult Index() { DailyMsg dailyMsg = new DailyMsg(); // here I'm assuming your stored proc returns the daily message without the id // you should update ViewDailyMessage() to return a DailyMsg dailyMsg.msg = dailyMsgs.ViewDailyMessage(); return View(dailyMsg); }添加html:
<div> @Model.msg </div>
文本應顯示在div.
理想情況下,您應該ViewDailyMessage()在資料層中更新以回傳您的DailyMsg模型而不是字串。
此外,請考慮重命名您的類和方法,因為它們目前命名不佳且令人困惑。您的資料層DailyMsgs和模型DailyMsg具有非常相似的名稱并執行完全不同的功能。
給他們適當的名字。我建議重命名如下:
// data layer
// DailyMsgs (rename) -> MessageDataProvider
public class MessageDataProvider
{
// rename ViewDailyMessage -> GetDailyMessage
public DailyMessageModel GetDailyMessage()
{
}
}
// model
// DailyMsg (rename) -> DailyMessageModel
public partial class DailyMessageModel
{
}
這樣你就可以從名稱中看出每個類的職責(一個是資料層,另一個是模型)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/407646.html
標籤:
