我如何动态地将新实体添加到我的Htmlhelper.dropdownlist中

时间:2012-03-12 14:19:10

标签: linq asp.net-mvc-3 search

我有以下操作方法启动SelectList,如下所示: -

        public PartialViewResult Search(string q, int q2,string q3,string sortOrder)
    {

    ViewBag.q2 = new SelectList(elearningrepository.FindAllLevels().ToList(), "DifficultyID", "Description", 2);
    ViewBag.q3 = new SelectList(elearningrepository.FindAllusers().ToList(), "UserID", "UserID",2);
    ViewBag.today = DateTime.Today;
    ViewBag.nextmonth = DateTime.Now.AddMonths(1);
    var v = elearningrepository.searchquestions3(q, q2, q3);
     return PartialView("_searchquestion", v);
        }

以下存储库方法: -

 public IQueryable<Question> searchquestions3(string q, int? q2 , string) 
            { 

   return from u in entities1.Questions 
   where (u.Description.Contains(q) && (u.DifficultyID == q2 || q2 == "Any" )  && ( u.CreatedBy == q3 || q3 == "Any"))                         
select u;}

然后在视图上我呈现下拉列表如下: -

<th>
@Html.DropDownList("q2")        
</th>
 </tr>
  <tr>
<th>
Seach By Create By:-
</th>
<th>
@Html.DropDownList("q3")
</th>

但是如何添加一个代表“任意”字的新值到q2&amp; q3下拉列表,以便存储库方法按预期工作? BR

3 个答案:

答案 0 :(得分:2)

首先,我建议您在处理更复杂的对象时使用ViewModels。你可以使用ViewBag实现它,但它很麻烦。

现在。在您可以执行的操作中:

var list = elearningrepository.FindAllLevels().ToList()
list.InsertAt(0, new TypeOfYourObject() {ValueProperty = "Any"});
ViewBag.q2 = new SelectList(list, "DifficultyID", "Description", 2);

您可以与其他人充分合作,但要认真考虑强类型的ViewModel。

答案 1 :(得分:0)

@Html.DropDownList("q3","Any")

您需要使用optionLabel

在您的控制器中

您收到了帖子。

无论你想做什么,例如。数据库事务,只有当值==空字符串或标签==“任何”

时才会执行

答案 2 :(得分:0)

Jquery的客户端解决方案

$("#Select_Id").append("<option value='0'>Text</option>");

如果要将其添加为第一个元素,可以使用.prepend()。