这看起来很糟糕。这应该怎么做呢? Asp.Net MVC 和下拉菜单
我正在学习 MVC 并在新的用户注册表单中的 MVC 应用程序上使用 DropDown。
对于我的大多数屏幕,我有两种控制器方法。一种用于 GET(屏幕的初始显示),另一种用于 POST(当用户单击“提交”按钮时)。
这是代码:
public ActionResult UserRegistration()
{
SelectList list = new SelectList(SiteUserRepository.GetTimezones(), "timezone_id", "location");
ViewData["timezones"] = list;
return View();
}
[HttpPost]
public ActionResult UserRegistration(SiteUserModels.SiteUserRegistrationModel model)
{
if (ModelState.IsValid)
{
SiteUserRepository.CreateUser(model.username, model.email, model.password, model.firstname, model.firstname, model.timezone_id);
return RedirectToAction("Index", "Home");
}
SelectList list = new SelectList(SiteUserRepository.GetTimezones(), "timezone_id", "location");
ViewData["timezones"] = list;
return View();
}
请注意,我正在复制并发布代码。正在复制下拉列表(SelectList)的代码。我发现 ViewData 仅适用于初始请求,因此我需要为 Post 重做它(如果用户输入了无效数据,则返回屏幕..)
是否有更好的方法来执行此操作?
I am learning MVC and using a DropDown on my MVC app in my new User Registration form.
As for most of my screens, I have two controller methods. One for the GET (initial display of the screen), and one for the POST (When the user clicks Submit button).
Here's the code:
public ActionResult UserRegistration()
{
SelectList list = new SelectList(SiteUserRepository.GetTimezones(), "timezone_id", "location");
ViewData["timezones"] = list;
return View();
}
[HttpPost]
public ActionResult UserRegistration(SiteUserModels.SiteUserRegistrationModel model)
{
if (ModelState.IsValid)
{
SiteUserRepository.CreateUser(model.username, model.email, model.password, model.firstname, model.firstname, model.timezone_id);
return RedirectToAction("Index", "Home");
}
SelectList list = new SelectList(SiteUserRepository.GetTimezones(), "timezone_id", "location");
ViewData["timezones"] = list;
return View();
}
Note that I am copying and posting code. The code for the drop down (The SelectList) is being copied. I found out that ViewData is only available for the initial request, so I needed to redo it for the Post (If the user has entered invalid data, the screen is returned ..)
Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的情况下,返回非发布操作的 ActionResult 应该可以。
通常,您希望通过附加数据向视图提供一些错误报告。在这种情况下,您可以将 SelectList 创建重构为单独的方法以避免冗余。
It should be ok to return the ActionResult of the non-post Action in your case.
Normally, you'd want to provide some error reporting to the View though with additional data. In that case, you'd refactor your SelectList creation into a separate method to avoid redundancy.