1

好的,這是我的問題。我試圖用我的角色填充@Html.DropDownListFor()減去Admin角色。這工作得很好,但它顯示的所有角色:使用MVC中的自定義方法填充@ Html.DropDownListFor()

@Html.DropDownListFor(m => m.RoleName, new SelectList(Roles.GetAllRoles())) 

然而,這顯示了所有的角色,包括Admin卷。

所以我創建了另一個類UserHelper.cs這個方法是basicly同樣的事情Roles.GetAllRoles()

public string[] GetUserRoles() 
    { 
     string[] userroles = null; 
     using (MainVeinDataDataContext conn = new MainVeinDataDataContext()) 
     { 
      userroles = (from r in conn.Roles 
         where r.Rolename != "Admin" 
         select r.Rolename).ToArray(); 
     } 
     return userroles; 
    } 

然而,作爲很新的MVC,我不知道如何將這種方法暴露於DropDownList的在視圖中。所以這不工作,無論我嘗試:

@Html.DropDownListFor(m => m.RoleName, new SelectList(GetUserRoles())) 

我不知道我失蹤了什麼,它讓我發瘋。希望有人知道我錯過了什麼。

+0

你有一個視圖模型對這一觀點? – Dirk

回答

6

視圖不應該負責從某些數據源提取數據。它只應負責操縱控制器以vie模型的形式傳遞的數據。

你試圖做的是反MVC模式。你在這個GetUserRoles方法中的代碼是控制器(或數據訪問層)的責任,它的結果應該是你的視圖模型的一部分。因此,例如,你將有以下視圖模型:

public class MyViewModel 
{ 
    public string RoleName { get; set; } 
    public IEnumerable<SelectListItem> UserRoles { get; set; } 
} 

,然後你將有一個控制器動作,將填充此視圖模型:

public ActionResult Foo() 
{ 
    // The GetUserRoles could also be part of a repository 
    // that you would invoke here 
    var userRoles = GetUserRoles(); 

    // Now construct the view model that you will pass to the view 
    var model = new MyViewModel 
    { 
     UserRoles = userRoles.Select(x => new SelectListItem 
     { 
      Value = x, 
      Text = x 
     }) 
    }; 
    return View(model); 
} 
在你看來

現在:

@model MyViewModel 

@Html.DropDownListFor(
    m => m.RoleName, 
    new SelectList(Model.UserRoles, "Value", "Text") 
) 
+0

你是天賜之物。我是MVC的新手,因爲我的生活無法弄清楚這一點。我把事情搞定了,現在它像夢一樣運作。這真的幫助我更好地理解MVC的關係和應該如何完成的事情。我敢肯定,我會在這裏發佈更多的問題,因爲這是我的第一個問題,但是你讓我擺脫了過早的禿頂! – Phatjam98

+0

@ phatjam98,如果此答案對您有幫助,請確保[標記爲此類](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work),方法是點擊你旁邊的勾號。 –

0

除非您已將名稱空間添加到您的web.config,否則您可能需要完全限定方法GetUserRoles()才能正確註冊。

0

我有模擬器的例子,很好地工作 在我的情況下,我需要填充從SQL表的大列表中選擇列表。

[在控制器]

public ActionResult GetDealTypes() 
    { 
     //Seleted Parameter 
     return GetReferenceCodesByType("Deal"); 
    } 


    private ActionResult GetReferenceCodesByType(string p_RefType) 
    { 
     IList<int> ArticleType = db.ReferenceTypes.Where(a => a.Code == p_RefType).Select(a => a.ID).ToList(); 

     var query = (from rt in db.ReferenceTypes 
        join rc in db.ReferenceCodeModels on rt.ID equals rc.ReferenceTypeId 
        where rt.Code == p_RefType 
        select new { rc.ID, rc.Description }).ToList(); 

     query.Insert(0, null); 
     //Keeping in ViewBag - Which I ll access in view page 
     ViewBag.DealTypes = query; 
     return View(); 
    } 

[在查看]

@Html.DropDownListFor(g => g.DealTypeId, new SelectList(ViewBag.DealTypes, "Id", "Description")) 

//ViewBag.DealTypes work as Data source which has been set in controller 
@Html.ValidationMessageFor(model => model.DealTypeId) 
相關問題