使用 DropdownListFor - 使用 Jquery 设置值,也在控制台中显示,但在控制器中为空

Using DropdownListFor - Value is being set using Jquery, Displayed in Console too, but Null at Controller

这是我的 Dropdown.

的语法
@Html.DropDownListFor(model => model.DealerIdRef, Model.Ddllist, " Select Dealer ", new { @class = "form-control"})

我想要它的默认选择值并将其设为只读,这样用户就无法更新选择。为此,我使用 Jquery.

$('#DealerIdRef').val('@Session["MyID"]').trigger('change');
$("#DealerIdRef").attr('disabled', 'true');

这是设置值,也存在于Console

在 Controller 中它仍然是空的

编辑

如果我犯了一些错误,请帮助。 提前致谢

我写了一个简单的模拟你的问题。

它可以工作。简单代码在DropDownController

这里是Source Code,我上传到github。

ViewModel

public class DropDownViewModel
{
    [Display(Name = "Dealer")]
    public int? DealerIdRef { get; set; }

    public IEnumerable<SelectListItem> Ddllist { get; set; }
}

索引视图

模拟您的提交操作

@model Sample.Models.DropDownViewModel

@using (Html.BeginForm("ShowDDL", "DropDown", FormMethod.Post))
{
    @Html.DropDownListFor(model => model.DealerIdRef, Model.Ddllist, " Select Dealer ", new { @class = "form-control" })
    <button>Submit</button>
}

ShowDDL 视图

显示您的 select 数据。

@model Sample.Models.DropDownViewModel

<b>Your Select Value: </b> @Model.DealerIdRef

DropDownController

public ActionResult Index()
{
    DropDownViewModel model = new DropDownViewModel()
    {
        Ddllist = GetDDL(),
        DealerIdRef = 1
    };

    return View(model);
}

[HttpPost]
public ActionResult ShowDDL(DropDownViewModel viewModel)
{
    return View(viewModel);
}

private IEnumerable<SelectListItem> GetDDL()
{
    return new List<SelectListItem>()
    {
        new SelectListItem()
        {
            Text = "One",
            Value = "1"
        },
        new SelectListItem()
        {
            Text = "Two",
            Value = "2"
        }
    };
}

您的 javascript 正在设置下拉列表的 disabled 属性。禁用的表单控件不提交值,因此模型中 DealerIdRef 的值是其默认值(即 null 因为它的 int?)。

如果要提交下拉列表的值,请不要禁用它。

但是基于我想要它的默认选择值并将其设置为只读以便用户无法更新选择,那么生成下拉列表就没有意义了,无论如何,您可以通过设置绑定到的 属性 的值来设置所选选项。也就是说,在将模型传递给视图之前,您在 GET 方法中设置了 DealerIdRef 的值。

因为您想要的只是显示一个值并将其回传,然后为该值包含一个隐藏的输入并显示文本

@Html.HiddenFor(m => m.DealerIdRef)
<div>...the txt you want to display...</div>

在不需要时生成 SelectList 和额外的 html 不会降低性能。

附带说明一下,您的 POST 方法会抛出 因为您在 [=37= 之前没有在 POST 方法中重新填充 SelectList ] 观点。