简体   繁体   English

在c#asp.net中返回View()时保留表单数据

[英]Keep form data when returning View() in c# asp.net

I am curious as to how one would keep the values of in the form when returning a View. 我很好奇如何在返回View时将值保留在表单中。 So say I had a email and password that must be entered to login and the user entered the email but not the password. 假设我有一个必须输入的电子邮件地址和密码才能登录,而用户输入的是电子邮件地址,而不是密码。 Is there any way that when I return the View I can keep the email there so the user just has to enter the password? 有什么方法可以让我在返回视图时将电子邮件保留在此处,以便用户只需输入密码?

This is my if statement: 这是我的if语句:

if (password == "")
{
    ViewBag.SpanText = "You must enter a password.";
    return View();
}

And these are the values being passed in: 这些是传入的值:

public ActionResult Login(string email, string password)

And this is the .cshtml: 这是.cshtml:

 <div class="input-group">
 <input type="text" class="form-control" name="email" placeholder="Email">
 </div>

 <div class="input-group">
 <input type="password" class="form-control" name="password" placeholder="Password">
 </div>

You need to return the View with the username and password variables. 您需要返回包含用户名和密码变量的视图。 So that razor can render it back. 这样剃须刀就可以将其还原。

if (password == "")
{
    ViewBag.SpanText = "You must enter a password.";
    return View(username, password);
}

Even better, you could create a LoginViewModel with username and password fields and work with the model. 更好的是,您可以使用用户名和密码字段创建LoginViewModel并使用该模型。 You can then use DataAnnotations to put password rules for the password field. 然后,您可以使用DataAnnotations为密码字段放置密码规则。

That way, when the user tries to login with a blank password, the page won't event post. 这样,当用户尝试使用空白密码登录时,该页面将不会发布事件。 Validation rules will kick in and they'll get an error message that you desire. 验证规则将生效,并且会收到您想要的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM