I already have the SQL Statement for retrieving data from the database, but I dont know how to pass the value from the class that I made to the controller and lastly to the view itself. I have tried to call the method for retrieving data from the database from the class that I made into the controller, and used ViewBag
--> ViewBag.Name
for save the value, and pass it to the view like this: @ViewBag.Name
. When I run, there is nothing to show, like the method for retrieving data is not called.
My question is, how to pass the value from the database and put it into the view?
Here is the code that I am using:
Controller:
[HttpGet]
public ActionResult Update()
{
ManageUser user = new ManageUser();
user.GetData(user.Username);
ViewBag.Username = user.Username;
ViewBag.EmployeeID = user.EmployeeID;
return View(user);
}
[HttpPost]
public ActionResult Update(ManageUser user)
{
if (ModelState.IsValid)
{
if (user.UpdateData())
{
return RedirectToAction("List", "Home");
}
else
{
ModelState.AddModelError(string.Empty, "Cannot update to the database!");
}
}
return View(user);
}
View:
@model ProjectName.Models.ManageUser
@{
ViewBag.Title = "Update";
}
<h2>Update</h2>
<br />
@using (Html.BeginForm())
{
@Html.ValidationSummary();
<div>
<fieldset>
<legend>Credentials Register</legend>
<div class="editor-label">
@Html.LabelFor(u => u.Username)
</div>
<div class="editor-field">
@ViewBag.Username
@Html.DisplayFor(u => u.Username)
</div>
<div class="editor-label">
@Html.LabelFor(u => u.EmployeeID)
</div>
<div class="editor-field">
@ViewBag.EmployeeID
@Html.DisplayFor(u => u.EmployeeID)
</div>
<input type="submit" value="Update »" />
<input type="button" value="Cancel »" />
</fieldset>
</div>
}
Class (ManageUser.cs):
[Required(ErrorMessage = "Please fill-in Username.")]
[Display(Name = "Username:")]
public string Username
{
get;
set;
}
[Required(ErrorMessage = "Please fill-in Employee ID.")]
[Display(Name = "Employee ID:")]
public string EmployeeID
{
get;
set;
}
public void GetData(string username)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
string query = "SELECT [Username], [EmployeeID] FROM [User] WHERE [Username] = @Username";
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@Username", SqlDbType.NVarChar);
if (string.IsNullOrEmpty(Username))
{
cmd.Parameters["@Username"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Username"].Value = username;
}
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Username = reader["Username"].ToString();
EmployeeID = reader["EmployeeID"].ToString();
}
}
else
{
reader.Dispose();
cmd.Dispose();
}
}
}
}
}