登录失败后将用户名传回到MVC视图/文本框

时间:2019-01-14 23:33:41

标签: c# asp.net-mvc knockout.js knockout-mvc

如果登录失败,我想保留用户名字段。我有一个名为“ user”的ViewModel对象,其中包含字符串Username

public class User
{
   public bool RememberMe { get; set; }
   public string Username { get; set; }
}

该信息通过

传递到控制器方法
login( User user )
{
    … validate user
    if (!valid)
    {
        ModelState.AddModelError("", "Login name or password is incorrect!");
        return View(user);  
    }
}

我验证了用户名确实存在于传递回视图的用户对象中。

现在在视图中我有这个:

@model Myapp.Models.User

<label class="form-label" for="form-signin-username">Username</label>
<input data-bind="value: loginViewModel.Username" class="form-control" id="form-signin-username" name="username" type="text" required="" placeholder="Username">

javascript是这样的:

var LoginViewModel = function () {
    self.UserName = ko.observable();
    self.Password = ko.observable();
    self.Authenticate = function (event) {
        var data = {
            UserName: self.UserName(),
            Password: self.Password()
        }
        xhr = $.ajax({
            data: data,
            dataType: 'JSON',
            type: "POST",
            url: "/Home/Login",
            success: function (data) {
            if (data.Success) {
            // process successful login ( this works)
            }
            else
            {
                // this is what doesn't work
                self.UserName = data.Username;  
            }
        }
    }
}

任何人都可以看到为什么该文本框不自动填充以前的用户名吗?

1 个答案:

答案 0 :(得分:0)

您需要确保将所需的模型值分配给视图模型

例如

var LoginViewModel = function () {
    self.UserName = ko.observable(@(Model.Username)); //set initial value
    //...

我还建议在视图中使用HtmlHelper作为输入

@model Myapp.Models.User

<!--...-->

@Html.LabelFor(m => m.Username, "Username")
@Html.TextBoxFor(m => m.Username, new { data_bind = "value: Username", @class = "form-control", placeholder="Username"})