Skip to main content
 首页 » 编程设计

c#之模型或 Controller 中的 Asp.net mvc 下拉代码

2024年02月13日14over140

我已经创建了具有注册页面的 ASP.NET MVC 4 Web 应用程序。它包含两个下拉项。

我想知道在哪里放置用于填充下拉项的代码是可行的。截至目前它在注册 Controller 中,但是由于服务器端验证,我在每种方法中编写了两次相同的代码。

注册索引

    public ActionResult Index() 
    { 
      var model = new RegisterModel 
      { 
       TitleList = new SelectList(DataAccess.DAL.DropDownValues("Title"), "Value", "Text"), 
       BankList = new SelectList(DataAccess.DAL.DropDownValues("Bank"), "Value", "Text") 
      }; 
     return View("Register", model); 
    } 

注册后操作

    [HttpPost] 
    [ActionName("doRegister")] 
    public ActionResult doRegister([Bind(Exclude = "TitleList")] RegisterModel registerModel) 
    { 
        var model = (RegisterModel)null; 
        if (ModelState.IsValid) 
        { 
            if (DataAccess.DAL.registerCustomer(registerModel)) 
            { 
                return RedirectToAction("Index", "Login"); 
            } 
        } 
        else 
        { 
            model = new RegisterModel 
            { 
             TitleList = new SelectList(DataAccess.DAL.DropDownValues("Title"), "Value", "Text"), 
             BankList = new SelectList(DataAccess.DAL.DropDownValues("Bank"), "Value", "Text") 
            }; 
        } 
        return View("Register", model); 
    } 

如果我没有使用下拉值初始化模型对象,它会在我的 View 中抛出错误

@Html.DropDownListFor(m => m.Title, new SelectList(Model.TitleList, "Value", "Text"), 
 "Select Title", new { @class = "form-control" }) 

我想知道我可以在哪里放置我的下拉代码?

请您参考如下方法:

您可以直接在 Controller 中创建函数并从两个位置调用它。我看不出有什么不妥。此外,您正在创建 SelectList 的实例,我认为这属于 Controller 的职责。

public RegisterModel FillModel() 
{ 
    return new RegisterModel 
            { 
                TitleList = new SelectList(DataAccess.DAL.DropDownValues("Title"), "Value", "Text"), 
                BankList = new SelectList(DataAccess.DAL.DropDownValues("Bank"), "Value", "Text") 
            }; 
}