我创建新员工时,下拉列表不会加载数据,但刷新页面时会加载新数据 [英] Dropdown is not loading data while I create new employee but when the page is refreshed it loads the new data

查看:91
本文介绍了我创建新员工时,下拉列表不会加载数据,但刷新页面时会加载新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我添加新员工时,插入的员工不会显示在下拉列表中,但是当我刷新整个页面时,下拉列表会显示我插入的数据。问题是添加新员工后下拉列表变空的原因。代码运行顺利,但我没有得到这背后的原因。
这是用户界面。在这里,我可以创建新的员工,然后可以将员工添加到网格中

When I add new employee the inserted employee does not show up in the drop down list but when I refresh the entire page the dropdowns shows the data I inserted. The problem is why the drop down list becomes empty after adding new employee. The code is running smoothly but I am not getting the reason behind this. This is the UI. Here I can create new Employees and then can add employees to the grid

这是模态视图,这里需要创建新员工的字段

This is the Modal View here the fields are needed to create a new staff

在这里你可以看到下拉列表是空的。但是当我刷新整个页面时,我可以在下拉列表中看到整个列表

但是当刷新整个页面时,插入的数据很好地显示了来自数据库的其他员工

现在让我们看看这里的代码部分,
这是我的模型

Now let us see the code part here, This is my model

 public class CompanyResource
{

    [Key]
    public int Id { get; set; }
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
    [StringLength(100)]
    public string Position { get; set; }
    [Display(Name="Date of Joining")]
    public DateTime? DOJ { get; set; }
    [StringLength(50)]
    public string Phone { get; set; }
    [StringLength(100)]
    public string Address { get; set; }
    [StringLength(1)]
    [Required]
    public string Status { get; set; }

    public virtual ICollection<ProjectResource> ProjectResources { get; set; }
    public virtual ICollection<ProjectSiteResource> ProjectSiteResources { get; set; }

}

这是我的控制器和行动

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Name,Position,DOJ,Phone,Address,Status")] CompanyResource companyResource)
    {

        var isAjaxRequest = Request.IsAjaxRequest();

        ModelState["Status"].Errors.Clear();

        if (ModelState.IsValid)
        {
            db.CompanyResource.Add(companyResource);
            db.SaveChanges();

            if (isAjaxRequest)
            {
                var staff = new SelectList(db.CompanyResource.ToList(), "Id", "Name");
                return Json(new { Flag = true, CompanyResources = staff }, JsonRequestBehavior.AllowGet);
            }

            Success(string.Format("Successfully save data !"), true);
            return RedirectToAction("Index");
        }
        if (!isAjaxRequest) return View(companyResource);
        return Json(null, JsonRequestBehavior.AllowGet);

    }


 public JsonResult GetStaff()
    {
        try
        {
            var staff = new SelectList(db.CompanyResource.ToList(), "Id", "Name");
            return Json(new { Flag = true, CompanyResources = staff }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new { Flag = false, Msg = ex.Message }, JsonRequestBehavior.AllowGet);
        }

    }

这是我的观点。脚本写在这里

This is my View. The scripts are written here

var optionsStaff = new AjaxOptions
{
    HttpMethod = "POST",
    //Confirm = "Do you want to add a new person?",
    //OnBegin = "OnBegin",
    OnSuccess = "OnSuccessStaff",
    OnComplete = "OnCompleteStaff",
    OnFailure = "OnFai lureStaff"
};

这是我的模态表格

<div class="modal fade" id="resourceStaffModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="staffModalTitle">Add Staff</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div class="panel-body">
                @using (Ajax.BeginForm("Create", "CompanyResources", null, optionsStaff, new { @id = "staffCreateForm" }))
                {
                    @Html.AntiForgeryToken()

                    <div class="form-horizontal">


                            <div class="form-group">
                                @Html.Label("Name", htmlAttributes: new {@class = "control-label col-md-2"})
                                @Html.ValidationSummary(true, "", new {@class = "text-danger"})
                                <div class="col-md-10">
                                    @Html.TextBox("Name", null, new { @class = "form-control" })

                                </div>
                            </div>

                        <div class="form-group">
                            @Html.Label("Position", htmlAttributes: new {@class = "control-label col-md-2"})
                            @Html.ValidationSummary(true, "", new {@class = "text-danger"})
                            <div class="col-md-10">
                                @Html.TextBox("Position", null, new {@class = "form-control"})

                            </div>
                        </div>

                        <div class="form-group">
                            @Html.Label("ToDate", "Date", htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-4">
                                @Html.TextBox("DOJ", null, new { @class = "form-control datepicker" })
                            </div>
                        </div>


                        <div class="form-group">
                                @Html.Label("Phone", htmlAttributes: new {@class = "control-label col-md-2"})
                                @Html.ValidationSummary(true, "", new {@class = "text-danger"})
                                <div class="col-md-10">
                                    @Html.TextBox("Phone", null, new {@class = "form-control"})

                                </div>
                            </div>


                            <div class="form-group">
                                @Html.Label("Address", htmlAttributes: new {@class = "control-label col-md-2"})
                                @Html.ValidationSummary(true, "", new {@class = "text-danger"})
                                <div class="col-md-10">
                                    @Html.TextBox("Address", null, new {@class = "form-control"})

                                </div>
                            </div>



                            <div class="form-group">
                                @Html.Label("Status", htmlAttributes: new { @class = "control-label col-md-2", @required = "required" })
                                <div class="col-md-10">
                                    <select class="form-control" id="Status" name="Status">
                                        <option value="A">Active</option>
                                        <option value="I">Inactive</option>
                                    </select>

                                </div>
                            </div>                                                 

                        <div class="modal-footer">
                            <div class="col-md-offset-2 col-md-10">
                                <button type="submit" class="btn btn-primary">Save</button>
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>                       
                }
            </div>
        </div>
    </div>
</div>

这是我的脚本从行动中收到Json回复

This is the script that I am receiving a Json response from the actions

    function OnBeginStaff() {}

    function OnCompleteStaff() {}

    function OnSuccessStaff() {
        $('#Name').val("");
        $('#Position').val("");
        $('#DOJ').val("");
        $('#Phone').val("");
        $('#Address').val("");
        $('#Status').val("");           

        $('#resourceStaffModal').modal('hide');
        $.get("@Url.Action("GetStaff", "CompanyResources")", function(resp) {
            if (resp.Flag) {
                $("#RName").empty().html("<option value>--Select--</option>");
                $.each(resp.GetStaff, function (key, item) {
                    $("<option>").attr("value", item.Value).html(item.Text).appendTo("#RName");
                });
            }
        });

    }

    function OnFailureStaff() {}


推荐答案

以下是您的控制器返回的内容:

Here is what your controller is returning:

return Json(new { Flag = true, CompanyResources = staff }, JsonRequestBehavior.AllowGet);
    }

请注意第二个属性 CompanyResources 。现在,您正在使用返回的数据:

Please note the 2nd property CompanyResources. Now here is what you are doing with the data returned:

$.each(resp.GetStaff, function (key, item) {
                $("<option>").attr("value", item.Value).html(item.Text).appendTo("#RName");
            });

看到你正在迭代 GetStaff 属性响应,但这是不正确的。您应该迭代 CompanyResources 属性。所以更改为:

See you are iterating the GetStaff property of the response but that is not correct. You should be iterating the CompanyResources property. So change to this:

 $.each(resp.CompanyResources, function (key, item) {
                $("<option>").attr("value", item.Value).html(item.Text).appendTo($("#RName"));
            });

同样斯蒂芬提到的,它应该是 .appendTo($(# RName)),而不是 .appendTo(#RName)我已在上面更改过。

Also as Stephen mentioned, it should be .appendTo($("#RName")), not .appendTo("#RName") which i have changed above.

这篇关于我创建新员工时,下拉列表不会加载数据,但刷新页面时会加载新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆