【问题标题】:MVC C# creating username passwordMVC C#创建用户名密码
【发布时间】:2018-10-20 10:18:17
【问题描述】:

我想创建包含用户名密码验证的 MVC 项目。但我不知道我该怎么做。我不会使用数据库。只需使用 getter setter 即可。我也会在模型课上这样做。我的吸气剂二传手在里面。我还必须预定义一些用户名密码。我将用户名密码写在文本中,并将其添加到问题中。谢谢您的任何想法

    public class Response
{   
    [Required(ErrorMessage = "Please enter your username")]
    public string Username { get; set; }

    [Required(ErrorMessage = "Please enter your password")]
    public string Password { get; set; }

}

    <form asp-action="Index" method="post">
    <div asp-validation-summary="All"></div>
    <p>
        <label asp-for="Username">Username : </label>
        <input class="form-control" asp-for="Username" />
    </p>

    <p>
        <label asp-for="Password">Password : </label>
        <input class="form-control" asp-for="Password" type="password" />
    </p>

    <button class="submit" type="submit">Login</button>
</form>

【问题讨论】:

    标签: c# authentication login asp.net-core-mvc


    【解决方案1】:

    基本上在您的视图中使用您的模型和 Html 助手:

    @model Response
    
    @using (Html.BeginForm("Index", "ControllerName", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationFor(m=>m.Username)
        @Html.TextBoxFor(m=>m.UserName)
       <button class="submit" type="submit">Login</button>
    }
    

    这样,当您提交表单时,Response 会被传递给控制器​​,其中包含数据。

    【讨论】:

    • 什么不起作用?请编辑您的问题并发布您的整个代码。
    • 让我解释一下我的代码请求。在我的 MVC 项目中,我有一个表单,我在标签中输入用户名和密码,如您所见。我还需要预定义用户名密码对,如 user 和 123 。在控制器中,我尝试使用字典来执行此操作,它没有给出错误,但它不起作用。我无法分享代码,因为这个地方太长了
    • [HttpGet] public ViewResult Index() { return View("Index"); } [HttpPost] public ViewResult Index(Response response) {Dictionary dictionary = new Dictionary();字典.Add("user1", "123"); if (ModelState.IsValid && dictionary.Keys.Equals(response.Username) && dictionary.Values.Equals(response.Password)) { Repository.AddResponse(response);返回视图(“主”,响应); }else { 返回视图() }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 2015-05-02
    • 2017-08-19
    相关资源
    最近更新 更多