且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取所选数据

更新时间:2023-12-03 16:23:16

首先解决为什么被加载任何数据。在你的更新()方法,你首先初始化ManageUser的一个新实例,其默认值为用户名(默认为typeof运算字符串)。然后调用 user.GetData(user.Username); 这通过来的方法和基于

 如果(string.IsNullOrEmpty(用户名))//它!
{
  cmd.Parameters [@用户名]值= DBNull.Value。
}

查询然后返回其所有用户的用户名字段是。如果数据库中未包含其中,用户名为空没有行返回任何行,为此没有数据显示。

然而,包括模型这种方法是不好的做法(以及有关其他方法,如获取所有用户是什么?)。通过将以下2类到你的数据文件夹启动

 公共接口IUserDB
{
  清单<使用者>取();
  用户获取(INT ID);
}
公共类USERDB:IUserDB
{
  公开名单<使用者>取()
  {
    清单<使用者>用户=新的List<使用者>();
    使用(SqlConnection的康恩=新的SqlConnection(的connectionString))
    {
      查询字符串=SELECT [用户名],[雇员] FROM [用户]
      conn.Open();
      使用(CMD的SqlCommand =新的SqlCommand(查询,康涅狄格州))
      {
        使用(SqlDataReader的读卡器= cmd.ExecuteReader())
        {
          而(reader.Read())
          {
            用户的用户=新用户();
            user.Username =读卡器[用户名]的ToString()。
            user.ID =读卡器[雇员]的ToString()。
            users.Add(用户);
          }
        }
      }
    }
    回报用户;
  }
  公众获取用户(INT ID)
  {
    用户的用户=新用户();
    使用(SqlConnection的康恩=新的SqlConnection(的connectionString))
    {
      查询字符串=SELECT [用户名],[雇员] FROM [用户],其中[雇员] = @ID;
      conn.Open();
      使用(CMD的SqlCommand =新的SqlCommand(查询,康涅狄格州))
      {
        cmd.Parameters.Add(@雇员,SqlDbType.Int).value的= ID;
        使用(SqlDataReader的读卡器= cmd.ExecuteReader())
        {
          如果(!reader.Read())
          {
            返回null;
          }
          user.ID =读卡器[雇员]的ToString()。
          user.UserName =读卡器[用户名]的ToString()。
        }
      }
    }
    返回用户;
  }
}

旁注:你并不需要调用的Dispose() - 在使用语句采用的照顾。该接口的目的可能不是很明显还没有,但是一旦你获得一定的经验和理解依赖注入将是。它不清楚为什么一个表名为用户将有一场名为雇员 - 它应该是用户名或更好的,只是 ID 。有没有需要调用如果(reader.HasRows)

然后你的类改为

 公共类用户
{
  [必需(的ErrorMessage =请填写用户名。)
  [显示(名称=用户名)]
  公共字符串用户名{获得;组; }  [必需(的ErrorMessage =请填写在雇员ID。)
  [显示(NAME =ID)]
  公共字符串ID {搞定;组; }
}

注:A类的名字应该反映它是什么,不是什么不 - 它不应该包含动词如管理

现在控制器,你可以可以调用这些方法来构建你的看法

 公共控制器UserController中:控制器
{
  USERDB _repository =新USERDB(); //以后你会使用DI
  公众的ActionResult指数()
  {
    清单<使用者>模型= _Repository.Fetch();
    返回查看(模型);
  }
  公众的ActionResult编辑(INT ID)
  {
    用户模型= _Repository.Get(ID);
    如果(型号== NULL)
    {
      返回新HttpNotFoundResult();
    }
    返回查看(模型);
  }
}

Index.cshtml 视图可能再像

  @model名单< yourAssembly.User>
@foreach(以型号VAR用户)
{
  @ Html.ActionLink(user.UserName,编辑,用户,新{ID = user.ID},NULL)
}

点击AA链接会通过用户 ID 值到编辑(INT ID)方法,它反过来会返回用户与该ID值。

请注意,你也 Edit.cshtml 视图需要包括编辑控件,即 @ Html.TextBoxFor(M = GT; m.UserName) ,而不是 @ Html.DisplayFor(M = GT; m.UserName)

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 &raquo;" />
            <input type="button" value="Cancel &raquo;" />
        </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();
                }
            }
        }
    }
}

Firstly to address why no data is being loaded. In your Update() method you first initialize a new instance of ManageUser, whose default value for Username will be null (the default for typeof string). You then call user.GetData(user.Username); which passes null to the method and based on

if (string.IsNullOrEmpty(Username)) // it is!
{
  cmd.Parameters["@Username"].Value = DBNull.Value;
}

your query then returns all Users whose Username field is null. If you database does not contain any rows where Username IS NULL no rows are returned, therefor there is no data to display.

However including this method in your model is bad practice (and what about other methods such as fetching all users?). Start by adding the following 2 classes to your Data folder

public interface IUserDB
{
  List<User> Fetch();
  User Get(int ID);
}
public class UserDB : IUserDB
{
  public List<User> Fetch()
  {
    List<User> users = new List<User>();
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
      string query = "SELECT [Username], [EmployeeID] FROM [User];
      conn.Open();
      using (SqlCommand cmd = new SqlCommand(query, conn))
      {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
          while (reader.Read())
          {
            User user = new User();
            user.Username = reader["Username"].ToString();
            user.ID = reader["EmployeeID"].ToString();
            users.Add(user);
          }
        }
      }
    }
    return users;
  }
  public User Get(int ID)
  {
    User user = new User();
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
      string query = "SELECT [Username], [EmployeeID] FROM [User] WHERE [EmployeeID] = @ID";
      conn.Open();
      using (SqlCommand cmd = new SqlCommand(query, conn))
      {
        cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = ID;
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
          if (!reader.Read())
          {
            return null;
          }
          user.ID = reader["EmployeeID"].ToString();
          user.UserName = reader["Username"].ToString();  
        }
      }
    }
    return user;
  }
}

Side notes: You do not need to call Dispose() - the using statement takes care of that. The purpose of the interface may not be obvious yet, but once you gain some experience and understand Dependency Injection it will be. Its not clear why a table named User would have a field named EmployeeID - it should be UserID or better, just ID. There is no need to call if (reader.HasRows).

Then change your class to

public class User
{
  [Required(ErrorMessage = "Please fill-in Username.")]
  [Display(Name = "Username:")]
  public string UserName { get; set; }

  [Required(ErrorMessage = "Please fill-in Employee ID.")]
  [Display(Name = "ID:")]
  public string ID { get; set; }
}

Notes: A class name should reflect what it is, not what is does - it should not contain verbs such as "Manage".

Now in the controller, you can can call these methods to construct your views

public Controller UserController : Controller
{
  UserDB _Repository = new UserDB(); // later you will use DI
  public ActionResult Index()
  {
    List<User> model = _Repository.Fetch();
    return View(model);
  }
  public ActionResult Edit(int ID)
  {
    User model = _Repository.Get(ID);
    if (model == null)
    {
      return new HttpNotFoundResult();
    }
    return View(model);
  }
}

Your Index.cshtml view might then look like

@model List<yourAssembly.User>
@foreach(var user in Model)
{
  @Html.ActionLink(user.UserName, "Edit", "User", new { id = user.ID }, null)
}

Clicking a a link will pass the users ID value to the Edit(int ID) method which in turn will return the User with that ID value.

Note also you Edit.cshtml view needs to include controls for editing, i.e @Html.TextBoxFor(m => m.UserName), not @Html.DisplayFor(m => m.UserName)