I am trying to learn ASP.NET MVC and ADO.NET. I am making a demo website in which there would be an admin panel. The admin would update the Daily Messages which will get reflected in the main homepage. I am using ASP.NET MVC. I have created the table in database as
create table DailyMsg
(
Sno int primary key,
msg varchar(max)
);
This is my Daily Access Layer
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;
}
}
My model class:
public partial class DailyMsg
{
public int Sno { get; set; }
public string msg { get; set; }
}
Now, I am stuck at this step. I don't know how to place this returned value simpleValue to the <h2> tag of my view.
My controller
DailyMsgs dailyMsgs = new DailyMsgs();
private amenEntities db = new amenEntities();
// GET: DailyMsgs
public ActionResult Index()
{
return View();
}
My home page:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
CodePudding user response:
Don't use webforms with MVC, use views instead.
- Create a view called
Index.cshtmlin theViews/Homedirectory. Or use the easy way - just right-click theIndex()action in the controller and selectAdd View... - Currently,
dailyMsgs.ViewDailyMessage()returns a string. You'll need to convert it to your model:// 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); } - At the top of the Index view add
and replace@model @<YourProjectName>.<Models>.DailyMsg<YourProjectName>.<Models>with the actual namespace whereDailyMsgclass resides - Add the html:
<div> @Model.msg </div>
The text should be displayed inside the div.
Ideally, you should update ViewDailyMessage() in the data layer to return your DailyMsg model rather than a string.
