为什么我从下拉列表中获取Id而不是Text?

时间:2015-07-27 05:22:01

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

我的家庭控制器看起来像这样

public ActionResult Index()
{
    List<District> allDistrict = new List<District>();
    List<Tehsil> allTehsil = new List<Tehsil>();
    List<SubTehsil> allSubTehsil = new List<SubTehsil>();
    using (FarmerBDContext db = new FarmerBDContext())
    {
        allDistrict = db.Districts.ToList();
    }
    ViewBag.DistrictId = new SelectList(allDistrict, "DistrictId", "DistrictName");
    ViewBag.TehsilId = new SelectList(allTehsil, "TehsilId", "Tehsilname");
    ViewBag.SubTehsilId = new SelectList(allSubTehsil, "SubTehsilId", "SubTehsilName");
    return View();
}

My District,Tehsil和SubTehsil下拉列表正在从另一个Model类填充。

地区类

public int DistrictId { get; set; }
public string DistrictName { get; set; }
public virtual ICollection<Tehsil> tbTehsils { get; set; }

我的Tehsil和Subtehsil课程类似,但与他们有关系

此模型类强烈地键入我的表单Index.cshtml

public string DistrictName { get; set; }
public string TehsilName { get; set; }
public string SubTehsilName { get; set; }
.... // Other Fields

我的索引视图就像这样

<table>
    <tr>
        <td class="editor-label Label">
            @Html.LabelFor(model => model.DistrictName)
        </td>
        <td>
            @Html.DropDownList("DistrictName", (SelectList)@ViewBag.DistrictId, " -- Select District -- ", new { @class = "ddl"})
        </td>
    </tr>
    <tr>
        <td></td>
        <td class="editor-field">
            @Html.ValidationMessageFor(model => model.DistrictName)
        </td>
    </tr>
    <tr>
        <td class="editor-label Label">
            @Html.LabelFor(model => model.TehsilName)
        </td>
        <td>
            @Html.DropDownListFor(model => model.TehsilName, @ViewBag.TehsilId as SelectList, "Select Tehsil", new { @class = "ddl" })
        </td>
    </tr>
    <tr>
        <td></td>
        <td class="editor-field">
            @Html.ValidationMessageFor(model => model.TehsilName)
        </td>
    </tr>
    ....
</table>

<p>
    <input type="submit" value="Details" />
</p>

我正在另外一个基于我的模型属性的控制器中访问它们。

ViewBag.DistrictName = model.DistrictName;
ViewBag.TehsilName = model.TehsilName;
ViewBag.SubTehsilName = model.SubTehsilName;

我还尝试使用下拉列表名称

访问下拉列表文本
Request.Form["DistrictName"].ToString()

甚至使用

FormCollection form

还有一点需要注意的是,当我使用简单的

<select>
<option id=1>Abc</option>
</select>

我收到的文字是Abc

1 个答案:

答案 0 :(得分:4)

因为<select>标记会回发其所选选项的value属性。你使用

ViewBag.DistrictId = new SelectList(allDistrict, "DistrictId", "DistrictName");

表示您的生成选项的value属性等于DistrictId的{​​{1}}属性。如果您检查生成的html,您会看到(假设您的集合包含Districtnew District() { DistrictId = 1, DistrictName = "ABC" };

new District() { DistrictId = 2, DistrictName = "XYZ" };

如果您希望将<select name="DistrictName" ...> <option value="1">ABC</option> <option value="2">XYZ</option> </select> 属性的值绑定到模型,则需要

DistrictName

或者你可以做

ViewBag.DistrictId = new SelectList(allDistrict, "DistrictName", "DistrictName");

附注:html表元素用于表格数据,而不是布局!