asp.net mvc剃刀文本框 [英] asp.net mvc Razor TextBox

查看:39
本文介绍了asp.net mvc剃刀文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查已在ASP.NET MVC @ Html.TextBox中输入的值并将其与数据库中的值进行比较?我想轻松登录,并查看文本框中输入的值是否与数据库中的值相同

How do you check the value that has been entered in an ASP.NET MVC @Html.TextBox and compare it with a value in the database? I want to make an easy login, and want to see if the value that has been entered in the textbox is the same as that in the database

<tr><td>Username</td><td>:</td><td>@Html.TextBox("username", new { @value = ViewBag.username })</td></tr>

我尝试了诸如创建一个viewbag并将其带到控制器的操作,但是它似乎没有用.

I tried things like creating a viewbag and then taking it to the controller, but it didnt seem to work.

推荐答案

为此特定UI创建视图模型(简单类)

Create a viewmodel(a simple class) for this specific UI

public class LoginViewModel
{
  [Required]
  public string UserName { set;get;}

  [Required]
  [DataType(DataType.Password)]
  public string Password { set;get;}
}

现在,在您的 GET 操作中,创建此类的对象并发送到您的视图.

Now in your GET action, create an object of this class and send to your view.

public ActionResult Login()
{
  var vm=new LoginViewMode();
  return View(vm);
}

现在在我们强类型化为LoginViewModel的登录视图(Login.cshtml)中,我们将使用TextBoxFor html helper方法来呈现 UserName Password 的文本框.代码>字段.

Now in our login view(Login.cshtml)which is strongly typed to our LoginViewModel, we will use the TextBoxFor html helper method to render the textboxes for our UserName and Password fields.

@model LoginViewModel
@using(Html.Beginform())
{
  UserName 
  @Html.TextBoxFor(x=>x.UserName);

  Password
  @Html.TextBoxFor(x=>x.Password)
  <input type="submit" />
}

这将呈现一个表单,该表单的动作属性值设置为/YourCotnroller/Login .现在我们需要一个 HttpPost 操作方法来处理表单发布

This will render a form which has action attribute value set to /YourCotnroller/Login. now we need to have an HttpPost action method to handle the form posting

[HttpPost]
public ActionResult Login(LoginViewModel model)
{
  if(ModelState.IsValid)
  {
    string uName=model.UserName;
    string pass=model.Password.

    //Now you can use the above variables to check it against your dbrecords.  
    // If the username & password matches, you can redirect the user to 
    //  another page using RedirecToAction method
    //  return RedirecToAction("UserDashboard")

  }
  return View(model);
}
public ActionResult UserDashboard()
{
  //make sure you check whether user is logged in or not
  // to deny direct access without login
  return View();
}

这篇关于asp.net mvc剃刀文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆