如何重新填充 html 帮助程序 DropDownListFor



我有一个负责从下拉菜单加载选项的方法。

当此视图首次加载时,该方法收到 null 参数,因此它不会尝试加载下拉菜单中的任何选项

现在,当用户键入一个数字时,该字段是 html 帮助程序 TextboxFor 并退出此控件,该方法将再次触发。

只有这一次,该方法才会将用户输入的值作为参数接收。

现在,当他收到此参数时,如果该方法将带来记录列表。

并将此列表分配给模型的属性,然后将其传递给视图。

但是,这就是问题所在,碰巧我无法使用发送到属性的列表更新模型的下拉菜单

我已经使用过ajax,但是根据公司的政治,我不允许使用本地主机向Web服务发出请求,这会破坏我的应用程序。

我还尝试追加JQUERY,但没有用。

尝试重新加载页面,但他删除了用户之前键入的所有其他值。

这是负责调用方法的函数,该方法将带来我需要从下拉菜单加载的选项列表

$("#DdlDocType").empty();
var a=document.getElementById('CodTranportista').value;
$.get("/Documents/Add",{codtransport:a}, null);

CodTransportista 是文本框的 ID,我从中获取将传递给该方法的值。

codtransport 是在代码隐藏中接收方法的变量的名称。

DdlDocType 是我分配给 HTML Helper DropDownListfor 的 id

这是DropDownList对于接收模型的Html

助手@Html.DropDownListFor(model => model.CarrierdtId, Model.SelectDocTypes, "No selection", new { id = "DdlDocType", @class = "col-xs-6 col-sm-4 col-md-6 col-lg-4 selectpicker show-menu-arrow modal-input" })

您可以创建一个呈现下拉列表的分部视图。将呈现分部视图的ActionResult接收类型化数字 (CodTranportista) 的值并填充下拉模型。要触发"ActionResult",您可以将 jQuery 事件onBlur添加到文本框中,以便每次字段失去焦点时,触发器都会发生。

另一种方法是这样的(但是我会反映公认的答案): ASP.NET MVC 级联下拉列表

为什么不将模型发布到该方法,更新其中的 SelectDocType,然后将其发送回视图,在这种情况下,您将拥有用户以前输入的所有数据。

编辑

我知道你提到你已经尝试过使用 jQuery append 但它没有用,但也许你缺少一些东西。 你能试试这种方法吗,我在我的项目中使用它,它工作得很好。

j查询:

var a=document.getElementById('CodTranportista').value;
$.ajax({
type: 'POST',
url: '/Documents/Add',
dataType: 'json',
data: { codtransport: a },
success: function (data) {
$("#DdlDocType").empty();
$.each(data, function () {
$("#DdlDocType").append('<option value="' + this.Value + '">' + this.Text + '</option>');
});
},
error: function (error) {
alert(error);
}
});

C#

public JsonResult Add(string codtransport)
{
var source = // Populate from somewhere
IEnumerable<SelectListItem> dropDownValues = source.Select(s => new SelectListItem()
{
Text = s.Name,
Value = s.Id
});
return new JsonResult { Data = dropDownValues , JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

相关内容

最新更新