MVC下拉选择(空白)选项

时间:2014-11-29 19:11:10

标签: asp.net-mvc drop-down-menu

我最初使用提交按钮设置了我的下拉菜单,这很好,但现在我想让它在没有按钮的情况下工作(我添加了onchange)。然而,现在我发现另一个困难,最初显示页面时,如果我"选择"第一个选项,没有任何事情发生(显然)所以我要添加"请选择"选项。我找到了几个解决方案,比如编写我的自定义SelectListOptions列表,但这似乎可能超出我的情况。任何人都可以在这里说清楚,让我知道这里最简单的选择是什么?对不起,如果这是简单的答案我真的卡住了。这是我的代码:

模型

public class SurveyDropdownModel
{
    public SelectList selectSurveys { get; set; }
    public string selectedId { get; set; }
    public IEnumerable<RespondentModel> respondents { get; set; }

    public SurveyDropdownModel(List<SurveyModel> surveys)
    {
        selectSurveys = new SelectList(surveys, "SurveyID", "SurveyTitle");
        respondents = null;
    }
}
public class SurveyModel
{
    [Required]
    [Display(Name = "Survey ID")]
    public int SurveyID { get; set; }

    [Display(Name = "Title")]
    public string SurveyTitle { get; set; }

    [Display(Name = "Updated")]
    public DateTime SurveyUpdatedDate { get; set; }

    [Display(Name = "Active")]
    bool IsActive { get; set; }
}        

控制器

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        HealthCheckDataLayer.HealthCheckRepository repo = new HealthCheckRepository(connectionString);

        List<SurveyModel> surveyList = repo.ReturnSurveys<SurveyModel>();
        var model = new SurveyDropdownModel(surveyList);
        return View(model);
    }
    [HttpPost]
    public ActionResult Index(SurveyDropdownModel model)
    { 
        //not important here 
    }
}

查看

@model HealthCheckWebApp.Models.SurveyDropdownModel
@{
    ViewBag.Title = "Home Page";
}

<div class="row">
     <div class="col-md-4">
        <h4>Select product:</h4>
        @using (Html.BeginForm("Index", "Home"))
        {
        @Html.DropDownList("selectedId", Model.selectSurveys, new { onchange = "this.form.submit()" }) 
        }
    </div>
</div>

<br />
<br />

@if(Model.respondents!=null)
{
@* not relevant here*@
}

我想现在我没有提供如何提取列表,我在那里从我的存储库调用存储过程(它需要用SP来完成)。

感谢。

1 个答案:

答案 0 :(得分:1)

使用@Html.DropDownListForHere是一种说明。

用法:

@Html.DropDownListFor(x=> x.selectedId, Model.selectSurveys, "Select something", new { onchange = "this.form.submit()" )
相关问题