IEnumerable<SelectListItem> list = items. Select(c => new SelectListItem { Text = c. CURRENCY_SYMBOL, Value = c. ID.
First we start off by creating a HTML dropdown on the page with an ID attribute. Next we create an AJAX POST in jQuery to a urlPath that will return the data we need in a JSON object. On the return of this AJAX request we are going to parse the response and use this in the helpers.
I have a view in place that contains 2 @DropDownListFor's Helpers:
@using (Html.BeginForm("CreateOneWayTrip", "Trips"))
{
@Html.ValidationSummary(false);
<fieldset>
<legend>Enter Your Trip Details</legend>
<label>Start Point</label>
@Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces, new { @Id = "province_dll", @class = "form-control" })
@Html.DropDownListFor(m => m.StartPointCity, (SelectList)ViewBag.Cities, new { @Id = "city_dll", @class = "form-control" })
<p style="float: none; text-align: center;">
<button type="submit" value="Create" class="btn btn-info btn-circle btn-lg">
<i class="fa fa-check"></i>
</button>
<button type="submit" value="Create" class="btn btn-warning btn-circle btn-lg">
<i class="fa fa-times"></i>
</button>
</p>
</fieldset>
}
Here is the temporary model I use to Capture data:
public class CaptureCreateTrip
{
[Required]
[Display(Name = "Trip ID")]
public string TripID { get; set; }
[Required]
public string StartPointProvince { get; set; }
[Required]
public string StartPointCity { get; set; }
}
One of the DropsDownList's are populated when the page is created and the second will be populated based on the option that the user chooses in the first DropDownList. To achieve this, i am using ajax. The javascript to I use looks like this:
$("#province_dll").change(function () {
$.ajax({
url: 'getCities/Trips',
type: 'post',
data: {
provinceId: $("#province_dll").val()
}
}).done(function (response) {
$("cities_dll").html(response);
});
});
Here is the Controller the AJAX calls:
[HttpPost]
public ActionResult getCicites(int provinceId)
{
var lstCities = new SelectList(new[] { "City1", "City2", "City3" });
return Content(String.Join("", lstCities));
}
Up until this point everything works - When I choose a value in my Province DropDown the javascript event fires and the Controller action does return the select list values to the Cities DropDown, the problem however is that the data(of the formatof the data) that the Action returns is incorrect. I Tested this by creating a Paragraph element and updating it's text with the return value of the ajax call, which is : "System.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItem"
*Note: I am new to ajax and in the process of learning Jquery and AJAX.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With