【问题标题】:I want to post dropdown text instead value in MVC DropdownFor我想在 MVC DropdownFor 中发布下拉文本而不是值
【发布时间】:2014-08-11 14:53:24
【问题描述】:

我想知道我是否有可能从 MVC 中的嵌套下拉列表中发布文本值??

我已经能够使用我的数据库值填充下拉列表,并且当它选择第一个下拉列表时,它会自动使用 json 结果填充第二个下拉列表。我想从下拉列表中发布文本值,可以吗??

这是我的带有 JSON 调用的控制器

[HttpPost]
public ActionResult Index(SchoolRegViewModel model, HttpPostedFileBase Logo)
{
    var queryCountry = _countryState.GetAllCountry().Select(s => new SelectListItem
    {
        Value = s.CountryId.ToString(),
        Text = s.CountryName,
        Selected = false
    });
    model.Country = queryCountry.AsEnumerable();

    var country = model.Country.Select(x => x.Text).Single();

    if (ModelState.IsValid)
    {
        try
        {
            ....
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    return View(model);
}

public JsonResult StateList(int? id)
{
    if (id != null)
    {
        var state = _countryState.GetAllState(id.Value);
        return Json(new SelectList(state, "CountryId", "StateName"), JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(new { }, JsonRequestBehavior.AllowGet);
    }
}

这是我的 jquery,用 json 结果填充第二个下拉列表

jQuery(function ($) {

$(function ()
{
    $('#CountryId').change(function () {
        $.getJSON('/Registration/Registration/StateList/' + $('#CountryId').val(), function (data) {
            var items = '<option>-- Select State --</option>';
            $.each(data, function (i, state) {
                items += "<option value = '" + state.Value + "'>" + state.Text + "</option>";
            });
            $('#State').html(items);
            $('#State option:selected').text();
        });
    });
});

});

查看

<div class="control-group">
    <label for="text" class="control-label">Country</label>
    <div class="controls">
    @Html.DropDownListFor(model => model.CountryId, Model.Country, "-- Choose Country --", new { id = "CountryId", required="true"})
    </div>
</div>

<div class="control-group">
    <label for="text" class="control-label">State/Provinces</label>
    <div class="controls">
        <select name="State" id="State" data-rule-required="true">
        </select>
    </div>
</div>

【问题讨论】:

    标签: javascript jquery asp.net-mvc json drop-down-menu


    【解决方案1】:

    只需使value 参数与您为文本输入的参数相同即可。

    new SelectList(state, "StateName", "StateName")
    

    还有:

    items += "<option value = '" + state.Text + "'>" + state.Text + "</option>";
    

    【讨论】:

    • 但是它仍然要发送 CountryId 让状态列表 Json 返回吗?因为我这样做了,但它没有返回状态列表,因为 json 没有获取 ID 而不是 Name 所以我如何绕过它来发送 json 的 ID 和数据库的 Post Text??
    • 你不能。过帐值是过帐值。您可以发布 id,然后使用 id 从数据库中查找内容以获取文本,在需要的情况下,否则,如果您想要文本,则必须发布文本。
    • 是的,我认为这是可能的,谢谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2014-06-10
    • 1970-01-01
    相关资源
    最近更新 更多