加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

使用ASP.Net MVC3中的jQuery动态填充下拉列表

发布时间:2020-12-16 00:10:13 所属栏目:asp.Net 来源:网络整理
导读:我有两个型号: public class ProfessorModels{ public string FullName { get; set; } public int ID { get; set; }} 和 public class ClassModels{ public int ID { get; set; } public string Professor { get; set; } public decimal Name { get; set; }
我有两个型号:
public class ProfessorModels
{
    public string FullName { get; set; }
    public int ID { get; set; }
}

public class ClassModels
{
    public int ID { get; set; }
    public string Professor { get; set; }
    public decimal Name { get; set; }
}

在我的视图中有一个表单来添加类:

@model MvcApp.Models.ClassModels

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ClassModels</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List","Index")
</div>

我想在课堂视图中添加一个下拉菜单,其中列出了所有可用的教授.教授在db中,我可以轻松地从控制器调用db并将所有教授加载到某个列表/数组中.
我需要帮助,如何使用jQuery与教授填充下拉列表.

解决方法

在你的控制器中:
[HttpGet]
    public virtual JsonResult LoadInfo()
    {
        var query = _repository.GetInformation(); //Here you return the data. 
        return Json(query,JsonRequestBehavior.AllowGet);
    }

然后在你看来:

<select id="info"></select>

然后使用jQuery加载下拉列表

function LoadInfo() {

    $.getJSON("@Url.Action(MVC.ControllerName.MethodName())",null,function (data) {

            $("#info").empty();

            $.each(data,function () {
                $("#info").append($("<option />").val(this.Id).text(this.Name));
            });

        });
}

这假定Id和Name是对象的属性.您可以使用ID和FullName,具体取决于您加载的下拉列表.我还使用T4MVC来获取不同的方法名称.

希望这可以帮助,

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读