msanabid
msanabid

Reputation: 197

Dropdown is not loading data while I create new employee but when the page is refreshed it loads the new data

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

Here you can see that the drop down is empty. But when I refresh the entire page I can see the whole list in the drop down

But when the entire page is refreshed the inserted data shows nicely with the other employees coming from the database

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; }

}

This is my Controller and actions

    [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"
};

This is my Modal form

<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>

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() {}

Upvotes: 0

Views: 588

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 27009

Here is what your controller is returning:

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

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");
            });

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"));
            });

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

Upvotes: 2

Related Questions