【问题标题】:How to bind value to dropdownlist in asp.net mvc?如何将值绑定到 asp.net mvc 中的下拉列表?
【发布时间】:2014-04-03 06:24:44
【问题描述】:

我有几个文本框和一个下拉列表,例如:

       for (int i = 0; i < count; i++)
       {
        <tr>
        <td>@Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { @id = "ddlProjectvalue" })
        </td>
        <td>@Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SUN_HRS, new { style = "width:50px; height:30px;", @class = "sunhrs" })
        </td>
        <td>@Html.TextBoxFor(m => m.GetTimeSheetDetails[i].MON_HRS, new { style = "width:50px; height:30px;", @class = "monhrs" })
        </td>
        <td>@Html.TextBoxFor(m => m.GetTimeSheetDetails[i].TUE_HRS, new { style = "width:50px; height:30px;", @class = "tuehrs" })
        </td>
        <td>@Html.TextBoxFor(m => m.GetTimeSheetDetails[i].WED_HRS, new { style = "width:50px; height:30px;", @class = "wedhrs" })
        </td>
        <td>@Html.TextBoxFor(m => m.GetTimeSheetDetails[i].THU_HRS, new { style = "width:50px; height:30px;", @class = "thurhrs" })
        </td>
        <td>@Html.TextBoxFor(m => m.GetTimeSheetDetails[i].FRI_HRS, new { style = "width:50px; height:30px;", @class = "frihrs" })
        </td>
        <td>@Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SAT_HRS, new { style = "width:50px; height:30px;", @class = "sathrs" })
        </td>
        </tr>
        </td>
        }

我想将数据库中的数据绑定到所有字段,每件事都完美地显示数据,但 proj_id 的下拉列表没有显示文本,即使我将值传递给下拉列表。我路过:

public int GetTimsheetData(int empid, TimesheetModel TimesheetModel)
{
    // GetimeSheet all the rows according employee name
    var emps = (from n in db.TIMESHEETs
                where n.RES_ID == empid
                select n).ToList();
    int count = emps.Count();
    HttpContext.Current.Session["count"] = count;
    try
    {
        List<TimesheetModel> emptyList = new List<TimesheetModel>();
        TimesheetModel.GetTimeSheetDetails = emptyList; //taking Empty List and bind to GetTimesheetDetails for Add items into it.


        //if Employee Name has more than one record.
        if (emps.Count() > 0)
        {
            foreach (var timeSheet in emps)
            {
                TimesheetModel item = new TimesheetModel();
                item.WEEK_CAL_ID = timeSheet.WEEK_CAL_ID;
                item.PROJ_ID = timeSheet.PROJ_ID;
                item.SUN_HRS = timeSheet.SUN_HRS;
                item.MON_HRS = timeSheet.MON_HRS;
                item.TUE_HRS = timeSheet.TUE_HRS;
                item.WED_HRS = timeSheet.WED_HRS;
                item.THU_HRS = timeSheet.THU_HRS;
                item.FRI_HRS = timeSheet.FRI_HRS;
                item.SAT_HRS = timeSheet.SAT_HRS;
                TimesheetModel.GetTimeSheetDetails.Add(item);

            }

        }

    }
    catch (Exception ex)
    {
        throw ex;
    }
    return count;
}

然后像这样返回控制器:

public ActionResult GetEmployeeDetails(int empId, string btn, TimesheetModel timesheetModel)
{
    Employer_BL employerBL = new Employer_BL();
    ViewBag.ProjectList = timesheetModel.getProjects;

    //If GetTimesheetData returns morethan one record 
    if (employerBL.GetTimsheetData(empId, timesheetModel) >= 0)
    {
        timesheetModel.EMP_ID = empId;

        //passes model data to View 
        return View("Timesheet", timesheetModel);
    }
    TimesheetModel model = new TimesheetModel();
    model.EMP_ID = empId;
    return View("Timesheet", model);
}

我在哪里做错了,下拉列表显示初始索引而不是显示传递值的文本。请任何人帮助我。

在单独的类中,我编写如下以获得项目名称:

    public SelectList getProjects()
    {
        IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
    return new SelectList(projectslist, "Value", "Text", PROJ_ID);
    }

【问题讨论】:

    标签: c# asp.net-mvc-4


    【解决方案1】:

    这取决于我在您的源代码中找不到的ViewBag.ProjectList。您可以使用 IEnumerable&lt;SelectListItem&gt; 类型的对象填充它,其中一项 Selected 属性设置为 true

    public IEnumerable<SelectListItem> GetList()
    {
        return (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() }).ToList();
    }
    

    在你的控制器上

    ViewBag.ProjectList = GetList();
    

    在你看来

    @{
        var projectList = 
            new SelectList(ViewBag.ProjectList, "Value", "Text", Model.GetTimeSheetDetails[i].PROJ_ID.ToString())
    }
    @Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, projectList, "-- Choose a Project --")
    

    【讨论】:

    • 我已经编辑并添加了获取项目名称的代码,请查看。
    • 您没有将结果发送到控制器中的ViewBag
    • 知道了。谢谢@qsoft。
    【解决方案2】:

    你可以试试这个方法:

    [NonAction]
    private IEnumerable<SelectListItem> GetData()
    {
        return new List<SelectListItem>()
        {
            new SelectListItem(){ Text="--Select--", Value="0"},
            new SelectListItem(){ Text="A", Value="1"},
            new SelectListItem(){ Text="B", Value="2"},
            new SelectListItem(){ Text="C", Value="3"},
        };
    }
    
    Call this function in Action Method
    public ActionResult Create()
    {
        ViewData["categories"] = GetData();
        return View();
    }
    
    
    On your html page:
      <%= Html.DropDownList("cat", (IEnumerable<SelectListItem>)ViewData["categories"])%>
    

    【讨论】:

    • 感谢线索,但我不想绑定所有数据,我想为下拉列表分配值以显示文本,因为我已经绑定数据,我想在我得到值时返回 empid 并取决于它显示文本 @Shashank 的值
    【解决方案3】:

    您可以使用 viewbag 。在您的控制器中,您可以从数据库中读取数据:

    public ActionResult Create()
    {
      ViewBag.ClassName = new SelectList(objclassrep.GetClasslist(), "Id", "ClassName");
    }
    

    在您的视图模型中,您可以像这样从控制器读取数据:

    <div class="editor-label">
                @Html.LabelFor(model => model.ClassId)
    </div>
    <div class="editor-field">
                @Html.DropDownListFor(x => x.ClassId, (SelectList)ViewBag.ClassName);
                @Html.ValidationMessageFor(model => model.ClassId)
    </div>
    

    此代码自动将您的数据 ID 绑定到 DDL 这是类 ID

    这是 getClassList 函数:

     public List<Class> GetClasslist()
            {
                return _dbcontext.Classes.ToList();
            }
    

    【讨论】:

    • 感谢线索,但我的下拉列表包含像 GetTimesheetDetails[index].Proj_Id 这样的列表,我需要将值传递给这个下拉列表,我像上面一样传递,但它不起作用.. @Iti Tyagi。
    • 正如您在我的回答中看到的,我将值传递给 DDL,这里是类 ID。您是否正确输入了 VIEWBAG 的名称?
    • viewbag 有效,但我需要以列表的形式传递值,该列表值应绑定到下拉列表,显示与值相关的文本,我以列表的形式传递值,但不工作。 @E A
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2018-02-04
    相关资源
    最近更新 更多