I very new to MVC and I have an issue that was real easy in webforms. I have a drop down list on a form. I have a button that loads a modal form that allows the user to add an item to the DB on the fly. I then need to update the dropdown list with the new contents of the table. I realize I need ajax to do this but I am very confused on how to initiate the update!
I have the form with the following dropdown.
<div class="form-group form-group-sm required">
@Html.LabelFor(m => m.ListingData.Transmission, new { @class = "col-md-4 control-label" })
<div class="col-md-8">
@Html.DropDownListFor(m => m.ListingData.Transmission, (SelectList)ViewBag.TransmissionList, new { @class = "form-control"} )
@Html.ValidationMessageFor(m => m.ListingData.Transmission, "", new { @class = "text-danger" })
<p class="form-text"><a data-modal='' href='@Url.Action("QATransmission", "Admin", new { ListingId = Model.ListingData.ListingId}))' id=''>Quick Add Manufacturer</a></p>
</div>
</div>
I use this ajax in the main page to call the load the list code in the controller.
$(function () {
$.ajax({
type: "GET",
url: "Admin/LoadTransmissionList",
data: JSON,
cache: false,
success: function (data) {
$.each(data, function (index, value) {
$('#Transmission').append('<option value="' + value.TransmissionText + '">' + value.TransmissionText + '</option>');
});
}
});
});
This is my controller code for the list:
[HttpPost]
public JsonResult LoadTransmissionList()
{
var lstTrans = db.Transmissions.ToList();
List<SelectListItem> list = new List<SelectListItem>();
foreach (Transmission p in lstTrans)
{
list.Add(new SelectListItem() { Value = p.TransmissionText.ToString(), Text = p.TransmissionText.ToString() });
}
return Json(list, JsonRequestBehavior.AllowGet);
}
I have a modal form and it has a text box for entering a new list item. I need to save to the DB, which works but then! I cant come up with the reload the listbox contents part. Any help!
Thanks!
1)Make your code changes like this
success: function (data) {
$('#ListingData_Transmission').html("")
$.each(data, function (index, value) {
$('#ListingData_Transmission').append('<option value="' + value.TransmissionText + '">' + value.TransmissionText + '</option>');
});
}
hope this should work now
2) Make your form as a partial view and reload it whenever your saving something to DB.
Let me know if any issues
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.