2016-07-26 109 views
-1

我有以下問題。MVC:DropdownListFor錯誤「無法將lambda表達式轉換爲類型'string',因爲它不是委託類型」

我有一個表叫做Users,我有另一個表叫Department

現在我想要的是,在用戶界面中,當用戶使用用戶表單創建自己時,他在部門字段中顯示下拉列表,可以從部門表中獲取所有部門標題。原因:部門表將用於其他操作,不應與用戶數據鏈接。所以用戶數據只能包含表格中的部門名稱,這就夠了。

我的控制器看起來是這樣的:

public ActionResult UserCreate() 
{ 
    ViewBag.AppDataDepartment = new SelectList(database.department, "department_title", "department_title"); 
    return View(); 
} 

[HttpPost] 
public ActionResult UserCreate(Users user) 
{ 
    if (user.UserID == "" || user.UserID == null) 
    { 
     ModelState.AddModelError(string.Empty, "UserID cannot be blank"); 
    } 
    try 
    { 
     if (ModelState.IsValid) 
     { 
      List<string> results = database.Database.SqlQuery<String>(string.Format("SELECT UserID FROM USERS WHERE UserID = '{0}'", user.UID)).ToList(); 
      bool _userExistsInTable = (results.Count > 0); 
      Users _user = null; 
      if (_userExistsInTable) 
      { 
       _user = database.Users.Where(p => p.UserID == user.UserID).FirstOrDefault(); 
       if (_user != null) 
       { 
        if(_user.active == true) 
        { 
          ModelState.AddModelError(string.Empty, "USER already exists!"); 
        } 
        else 
        { 
         database.Entry(_user).Entity.active = true; 
         database.Entry(_user).Entity.Last_Modified = System.DateTime.Now; 
         database.Entry(_user).State = EntityState.Modified; 
         database.SaveChanges(); 
         return RedirectToAction("Index"); 
        } 
       } 
      } 
      else 
      { 
       _user = new Users(); 
       _user.UserID = user.UserID; 
       _user.lastname = user.lastname; 
       _user.firstname = user.firstname; 
       _user.mail = user.mail; 
       _user.department = user.department; 
       _user.user_image = user.user_image; 
       _user.image_path = user.image_path; 
       if (ModelState.IsValid) 
       { 
        _user.active = true; 
        _user.Last_Modified = System.DateTime.Now; 
        database.Users.Add(_user); 
        database.SaveChanges(); 
        ViewBag.AppDataDepartment = new SelectList(database.department, "department_title", "department_title"); 
        return RedirectToAction("Index"); 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     //return base.ShowError(ex); 
    } 
    return View(user); 
} 

這是我的HTML部分:

<div class="row"> 
    @Html.LabelFor(model => model.UserID, "UserID", new { @class = "col-sm-2 control-label" }) 
    <div class="col-md-4"> 
     @Html.TextBoxFor(model => model.UserID, new { @class = "col-md-4 control-label form-control", @id = "inputEmail3" }) 
    </div> 

    @Html.LabelFor(model => model.department, "Department", new { @class = "col-sm-2 control-label" }) 
    <div class="col-md-4"> 
     @Html.DropDownList(model => model.department, (SelectList) ViewBag.AppDataDepartment, htmlAttributes: new { @class = "form-control" }) 
    </div> 
</div> 

而且從表中最後我的部門類:

[Table("department")] 
public partial class department 
{ 
    [Key] 
    public int departmentid { get; set; } 
    [Required] 
    public string department_title { get; set; } 
    public string subdepartment { get; set; } 
} 

但我不能編譯,因爲我得到錯誤:

Error CS1660 Cannot convert lambda expression to type 'string' because it is not a delegate type BTKPI

爲什麼這不起作用?我該如何解決這個問題?

我已經看過這個SolutionProposal,但這沒有幫助,因爲模型Linq和Data.Entity已經被引用。

+3

'@ Html.DropDownListFor()''不@ Html.DropDownList()' –

+0

@StephenMuecke感謝,但後來我得到了以下錯誤消息: 錯誤CS1928 \t '的HtmlHelper ' 不包含「DropDownListFor的定義'和最好的擴展方法重載'SelectExtensions.DropDownListFor (HtmlHelper ,Expression >,IEnumerable ,object)'有一些無效的參數 – Azeristar

+0

你有這麼多不好的代碼一個奇蹟什麼都有效。你綁定的模型是什麼? (你所顯示的只是'class department',但不包含名爲'department'的屬性) –

回答

2

它需要DropDownListFor(),不DropDownList()

@Html.DropDownListFor(m => m.department, (SelectList)ViewBag.AppDataDepartment, new { @class = "form-control" }) 

如果你使用DropDownList(),那麼這將是

@Html.DropDownList("department", (SelectList)ViewBag.AppDataDepartment, new { @class = "form-control" }) 

但是也有你的代碼許多其他問題,您應該解決。

  1. 你的控制器應UserController和方法Create() 以便將URL ../User/Create,不User/UserCreate
  2. 你編輯的數據,所以你應該使用視圖模型(不使用 數據模型編輯時數據) - 參考What is ViewModel in MVC?, 並且視圖模型應該包含屬性 IEnumerable<SelectListItem> DepartmentList-典型示例是在this question/answer中示出的 。
  3. Users表應存儲的DepartmentID, 不是它的名稱,應該有到 Departments表中的FK關係。
  4. UserID您的視圖模型屬性應該有一個[Required] 屬性和視圖應該包括@Html.ValidationMesageFor(m => m.UserID),讓你得到博特客戶端和服務器端驗證(同上爲DepartmentID屬性)。你也應該考慮 應用了RemoteAttributeUserID屬性,以便 您獲得客戶端驗證 - 指How to: Implement Remote Validation in ASP.NET MVC

最後,幾乎沒有什麼是你POST方法是使多大意義。您調用數據庫兩次以檢查用戶是否已經存在。您多次檢查ModelState.IsValid。您的user_imageimage_path屬性表明您需要上傳圖片,但無處保存。您分配ViewBag.AppDataDepartment,然後立即重定向到Index()方法。你的代碼看起來應該像(忽略文件上傳問題)

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create(UserVM model) 
{ 
    // Return early 
    if (!ModelState.IsValid) 
    { 
     // You will enter this automatically of UserID is null 
     model.DepartmentList = ... // assign the SelectList 
     return View(model); 
    } 
    // One database call to check if the user exists 
    User user = database.Users.Where(p => p.UserID == model.UserID).FirstOrDefault(); 
    if (user != null && !user.active) 
    { 
     user.active = true; 
     // Save and redirect 
    } 
    else if (user != null) 
    { 
     ModelState.AddModelError(string.Empty, "USER already exists!"); 
     model.DepartmentList = ... // assign the SelectList 
     return View(model); 
    } 
    user = new User 
    { 
     UserID = model.UserID, 
     lastname = model.lastname, 
     .... // set other properties of User 
     Last_Modified = System.DateTime.Now 
    } 
    // Save and redirect 
} 

儘管其原因尚不清楚誰已封存的現有用戶將需要導航到Create()方法(和提交表格填寫全他們之前已經輸入的很多細節)。您應該有一個單獨的方法來激活以前存檔的用戶。

+0

其實這是管理員用戶控制。我已經實現了一個RBAC模型,它具有角色,權限和用戶。他們都在一個控制器管理員中。這就是爲什麼我有CreateUser這樣的動作名稱,因爲我也有CreateRole&CreatePermission。你有postes的鏈接是非常有幫助的。 – Azeristar

+0

然後你應該使用[Areas](http://www.codeguru.com/csharp/.net/net_asp/mvc/article.php/c20227/Using-Areas-in-ASPNET-MVC-Application.htm) –

+0

謝謝,這聽起來很合邏輯。我會盡力今天實施:)感謝您的幫助和鏈接。 – Azeristar