Search code examples
javascriptc#jqueryasp.net-coreknockout-mvc

How do you bind your dynamic ASP.NET DropDownListFor() with the stored value in the database using knockout data binding in the Edit form


I have a working Form which dynamically fetches the data from the database, updates it and stores it in the database.However, I have an issue in dynamically binding a dropdown picklist to the current value stored in the database while Editing.

The issue I face is with the picklist dropdown field, when it is loaded in the Edit form, it is not bound to the current value of that field in the database, as a work around to it, I create a disabled field with the current value in the database, and a second dropdown field for the picklist. The edit form on the ajax post picks up the value in the dropdown field and stores it into the database. Now you can guess the issue is that when the user does not even touch the dropdown field from the picklist, the default value gets posted and gets stored in the database hence editing it without the user noticing.

<div class="row" id="editProspectMeasuredStructurFormDiv" data-bind="with:EditModel">


@using (Html.BeginForm("Edit", "ProspectMeasuredStructure", FormMethod.Post, new { @class = "form-group", @id = "editForm" })){
      @Html.TextBoxFor(m => m.MeasuredStructureId, new { @class = "form-control", data_bind = "value: MeasuredStructureText", disabled = "disabled" })
<label>The MeasuredStructureis listed as:</label>

     @Html.DropDownListFor(m => m.MeasuredStructureId, new SelectList(Model.MeasuredStructures, "MeasuredStructureId", "Name"), new { @class = "form-control", @id = "editMeasuredStructureId", placeholder = Html.DisplayNameFor(m => m.MeasuredStructureId) })
     @Html.LabelFor(m => m.MeasuredStructureId)
     <input type="submit" class="btn btn-action" value="Submit" id="submitEditMeasuredStructure" data-bind="click: function(){$root.EditMeasuredStructure();}" />
}
</div>
 var prospectMeasuredStructureModel = function (parent, prospectMeasuredStructureId, prospectId, prospectText, measuredStructureId, measuredStructureText{
 var self = this;
        self.ProspectMeasuredStructureId = ko.observable(prospectMeasuredStructureId);
        self.ProspectId = ko.observable(prospectId);
        self.ProspectText = ko.observable(prospectText);
        self.MeasuredStructureId = ko.observable(measuredStructureId);
        self.MeasuredStructureText = ko.observable(measuredStructureText);
        self.EditModel = ko.observable();
}



var prospectMeasuredStructureViewModel = function () {
        var self = this;
        self.ProspectMeasuredStructureId = ko.observable();
        self.ProspectId = ko.observable();
        self.ProspectText = ko.observable();
        self.MeasuredStructureId = ko.observable();
        self.MeasuredStructureText = ko.observable();
        self.EditModel = ko.observable();

        self.EditMeasuredStructure = function () {
            self.ProspectMeasuredStructureId = $('#editProspectMeasuredStructureId').val();
            self.ProspectId = $('#hfProspectId').val();
            self.MeasuredStructureId = $('#editMeasuredStructureId').val();
            self.Address = $('#editAddress').val();

            $.ajax({
                url: '@Url.Action("Edit", "ProspectMeasuredStructure")',
                type: 'POST',
                data: JSON.stringify(self),
                contentType: 'application/json; charset=utf-8',
                dataType: 'JSON',
                success: function (response) {
                    if (response.success) {
                        self.GetMeasuredStructures();
                        $('#editForm').hide();
                        alert("Edit Worked");
                    } else {
                        alert("Edit did not work");
                    }
                }
            });
        }
  [HttpPost]
        public ContentResult GetMeasuredStructures([FromBody] ProspectMeasuredStructureViewModel measuredStructureVM)
        {
            //Guid ProspectId = Guid.Parse(measuredStructure.ProspectId);
            var prospectMS = repository.Get(c => !c.Delete && c.ProspectId== measuredStructureVM.ProspectId);
            foreach (var item in prospectMS)
            {
                ProspectMeasuredStructureViewModel pVM = new ProspectMeasuredStructureViewModel();
                pVM.ProspectMeasuredStructureId = item.ProspectMeasuredStructureId;
                pVM.ProspectId = item.ProspectId;
                pVM.ProspectText = listManager.GetProspect(item.ProspectId).Name;
                pVM.MeasuredStructureId = item.MeasuredStructureId;
                pVM.MeasuredStructureText = listManager.GetMeasuredStructure(item.MeasuredStructureId).Name;
                prospectMeasuredStructureVModels.Add(pVM);
            }
            return new ContentResult()
            {
                Content = JsonConvert.SerializeObject(prospectMeasuredStructureVModels),
                ContentType = "application/json"
            };
        }

I am not sure how to bind the @Html.DropDownListFor() with the saved value which was added when the user first added the measured structure. As I said before, it shows the picklist correctly, what it does not do is "show the currently saved value as the first value". Hence it causes the default value to be saved to the database.

Kindly let me know if there is more code, if that needs to be posted, as I tried to take as many snippets as I thought were sufficient to explain my issue.


Solution

  • All I had to do was bind the dropdown list with the ID and that translated as the default value of the drop down list along with other picklist values in my view where the DropDownList was being declared.

      @Html.DropDownListFor(m => m.MeasuredStructureId, new SelectList(Model.MeasuredStructures, "MeasuredStructureId", "Name"), new { @class = "form-control", @id = "editMeasuredStructureId", placeholder = Html.DisplayNameFor(m => m.MeasuredStructureId),data_bind = " value: MeasuredStructureId" })
      @Html.LabelFor(m => m.MeasuredStructureId)