gpt4 book ai didi

asp.net-mvc-3 - 返回 View 时如何保持相同的数据?

转载 作者:行者123 更新时间:2023-12-04 05:43:43 24 4
gpt4 key购买 nike

返回 View 时如何保持相同的数据?

我试图将表单返回到 View ,但它没有用。

有没有什么好的和简单的方法来做到这一点?

[HttpPost]
public ActionResult Register(FormCollection form)
{
string name = form["Name"].Trim();
if (string.IsNullOrEmpty(name))
{
TempData["TempData"] = "Please provide your name ";
return View(form);
}

string email = form["Email"].Trim();
var isEmail = Regex.IsMatch(email, @"(\w+)@(\w+)\.(\w+)");
if (!isEmail)
{
TempData["TempData"] = "Sorry, your email is not correct.";
return View(form);
}

//do some things
}

最佳答案

不知道你为什么要使用 FormCollection在帖子中,但也许您来自 WebForms 背景。在 MVC 中,您应该使用 ViewModel 将数据传输到 View 和从 View 传输数据。

默认情况下 Register MVC 3 应用程序中的方法使用 Register 中的 ViewModel查看。您应该简单地将其发回。事实上,如果您不知道作为 Internet 模板的一部分,默认应用程序已经为您创建。

标准模式是拥有一个 ViewModel 来表示您将在 View 中使用的数据。例如,在您的情况下:

public class RegisterViewModel {

[Required]
public string Name { get; set; }

[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
}

你的 Controller 应该包含 2 个 Action ,一个 Get和一个 Post . Get呈现 View 并准备好供用户输入数据。提交后查看 Post然后调用 action。 View 将 ViewModel 发送到操作,然后该方法采取操作来验证和保存数据。

如果数据存在验证错误,将 ViewModel 返回到 View 并显示错误消息非常简单。

这是 Get行动:
public ActionResult Register() {
var model = new RegisterViewModel();
return View(model);
}

这是 Post行动:
[HttpPost]
public ActionResult Register(RegisterViewModel model) {
if(ModelState.IsValid) { // this validates the data, if something was required, etc...
// save the data here
}
return View(model); // else, if the model had validation errors, this will re-render the same view with the original data
}

您的 View 看起来像这样
@model RegisterViewModel

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Name) <br />
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Email) <br />
@Html.ValidationMessageFor(model => model.Email)
</div>
}

使用其他策略在 MVC 应用程序中捕获和保存数据是绝对可能的,它是一个非常可扩展的框架。但是有一种特定的模式使 MVC 成为现在的样子,并且有时会证明反对该模式很困难。对于初学者来说,最好先了解喜欢的模式和策略,一旦理解得非常好,然后就可以采用一些自己的自定义策略来满足您的需求。到那时,您应该充分了解系统,知道您需要更改什么以及在哪里更改。

快乐编码!!

关于asp.net-mvc-3 - 返回 View 时如何保持相同的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10959508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com