获取所选数据

时间:2015-06-12 04:56:36

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我已经有了从数据库中检索数据的SQL语句,但我不知道如何将值从我所做的类传递给控制器​​,最后传递给视图本身。我试图调用该方法从我在控制器中创建的类中检索数据库中的数据,并使用ViewBag - > ViewBag.Name用于保存值,并将其传递给视图,如下所示:@ViewBag.Name。当我运行时,没有任何东西可以显示,就像没有调用检索数据的方法一样。

我的问题是,如何从数据库中传递值并将其放入视图中?

以下是我正在使用的代码:

控制器

[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);
}

查看

@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>
}

类(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();
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

首先解决没有加载数据的原因。在Update()方法中,您首先初始化一个新的ManageUser实例,其Username的默认值为null(typeof string的默认值)。然后,调用user.GetData(user.Username);,将null传递给方法并基于

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

然后,您的查询将返回Username字段为null的所有用户。如果数据库不包含Username IS NULL没有返回任何行的任何行,则无法显示数据。

但是在您的模型中包含此方法是不好的做法(那么其他方法如获取所有用户呢?)。首先将以下两个类添加到Data文件夹

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;
  }
}

附注:您无需致电Dispose() - using声明可以解决这个问题。界面的目的可能还不明显,但是一旦你获得了一些经验并理解了依赖注入,它就会出现。不清楚为什么名为User的表会有一个名为EmployeeID的字段 - 它应该是UserID或更好,只有ID。无需拨打if (reader.HasRows)

然后将课程改为

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; }
}

注意:类名应该反映它是什么,而不是它的作用 - 它不应该包含诸如“管理”之类的动词。

现在在控制器中,您可以调用这些方法来构建视图

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);
  }
}

您的Index.cshtml视图可能会显示为

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

点击链接会将用户ID值传递给Edit(int ID)方法,而User方法会返回带有该ID值的Edit.cshtml

另请注意,您@Html.TextBoxFor(m => m.UserName)视图需要包含编辑控件,即@Html.DisplayFor(m => m.UserName),而不是org.jsoup.nodes.Element

答案 1 :(得分:0)

请参考他的。

您的数据访问方法将是。

public ManageUser GetData(string username)
{
    var result=new ManageUser();
    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())
                         {                                  
                                result.Username = reader["Username"].ToString();    
                                result.EmployeeID = reader["EmployeeID"].ToString();
                          }
                     }    
                     else
                     {
                          reader.Dispose();    
                          cmd.Dispose();
                      }
                 }
           }
           return result;
  }


        }

您的GET操作将是

[HttpGet]
public ActionResult Update(string username)
{
     ManageUser user = new ManageUser();    
     user =GetData(username);//call data access            
     return View(user);
}

上面的数据访问方法应该从Model转移到其他地方(可以作为私有方法的控制器)。

视图保持不变。

希望你明白了。