ViVi ViVi - 1 month ago 10
C# Question

Adding an item to a dropdownlist which is in another partial view without refreshing the view

I am new to asp.net mvc and I am facing this issue with dropdownlist now.
Sorry if I am asking a stupid question.

I have a main View

AbcView
which is bound to a Controller
AbcController
which passes an
AbcModel
to the view.

I have 2 partial views inside this
AbcView
which are loaded on button clicks.

Inside the second partial view, I have this code :

@Html.DropDownListFor(model => Model.TrajectoryName, new SelectList(@Model.Trajectories, "Value", "Text"),
new { @class = "dropdown-leftandright", id = drpTrajectory" })


Inside the first partial view, I have some data which is being added to database on some button click like this :

function deleteAction(trajID) {
$.ajax({
type: "POST",
url: "/AbcView/DeleteAction",
data: JSON.stringify({ deleteTraj: trajID }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
// I want to update the drpTrajectory dropdownlist here
},
error: function (e) {
return "error";
}
});
}


My issue is I want to access the
drpTrajectory
in second partial view inside this function. I want to add some item to this particular drop down list.
I tried to access the dropdownlist by using
$('#drpTrajectory')
and tried to add an item. But it is failing.

I tried to add data like this

$('#drpTrajectory ').add(val(data.x).text(data.y));


data
will be a member from a
IEnumerable<SomeClass> dataList
and
SomeClass
contains
id
and
name
which could be the value and text respectively.

I am already updating the model data during the button click ie
@Model.Trajectories
is getting updated.

So please help me to add an item to this dropdownlist which is in second partial view from my first partial view without refreshing the entire view.
Any idea?

Answer

Assuming your method is returning a collection of objects, then to create and append an option to a <select> you need

var select = $('#drpTrajectory') // cache it
$.ajax({
    type: "POST",
    url: '@Url.Action("DeleteAction", "AbcView")',
    data: { deleteTraj: trajID },
    dataType: "json",
    success: function (data) {
        select.empty() // if you need to remove the existing options
        $.each(data, function (index, item) {
            // Create an option element
            var option = $('<option></option>').val(item.id).text(item.name);
            // append it to the select element
            select.append(option);
        })
    },
    ....
});

Side notes

  1. Always use @Url.Action() to ensure that your url's are correctly generated
  2. There is no need to stringify() the data and then add the contentType` option
  3. Your controller method should be returning a collection of anonymous objects containing just the 2 properties you need (there is no point sending back extra data that's not use)

    var data = dataList.Select(x => new { id = x.id, name = x.name });
    return Json(data)
    
  4. Your use of new SelectList(@Model.Trajectories, "Value", "Text") suggests that the property Trajectories is already IEnumerable<SelectListItem>. If that is the case, there is no point creating an identical SelectList from the original one, so just use

    @Html.DropDownListFor(model => Model.TrajectoryName, Model.Trajectories, new { @class = "dropdown-leftandright", id = drpTrajectory" })
    
  5. The DropDownListFor() method is already creating id="TrajectoryName" so there is no real need to overwrite it by using new { id = drpTrajectory" }