0

OK so I'm happier with C# than Javascript and I'm happy that I can handle dropdownlist changes in my controller. here's a province dropdownlist:

@Html.DropDownList( "Province", null, htmlAttributes: new { @class = "form-control", @onchange = "document.location.href = '/Employees/FillDDLWithTowns?id=' +ID.value + '&provinceName=' + Province.value;" } ) 

In my controller I want to populate towns in the selected province, it all works well but why must the page refresh? Is there anyway to just populate the DDL without recourse to saving the record and re-displaying the page?

public ActionResult FillDDLWithTowns( int? id, string provinceName ) { if ( id == null ) { return new HttpStatusCodeResult( HttpStatusCode.BadRequest ); } tblEmployee tblASEmployee = db.tblEmployees.Find( id ); if ( tblEmployee == null ) { return HttpNotFound(); } if ( provinceName.Equals( "" ) == false ) { tblEmployee.Province = provinceName; db.Entry( tblEmployee ).State = EntityState.Modified; db.SaveChanges(); var postCode = Provinces.NamesAndPlaces.Instance.getPostCode( provinceName ); if ( postCode != 0 ) { SelectList municips = new SelectList( Provinces.NamesAndPlaces.Instance.getMunicipalities( postCode ) ); ViewBag.Town = municips; } } return Redirect( Request.UrlReferrer.AbsoluteUri.ToString() ); } 

Must I really revert to JQuery and JSON?

1
  • 7
    Must I really revert to JQuery and JSON? if you don't want the page to refresh, then yes. You would need to use AJAX, or whatever abstraction of it which ASP.Net allows you to use.CommentedOct 20, 2015 at 8:49

2 Answers 2

1

ASP.NET MVC is a server side technology. To populate a dropdown list without refreshing/re-requesting your page, you need a client side script - which Javascript is.

jQuery or JSON are not really required, you could do this using plain vanilla Javascript and you could use another method to format the data, but the most convenient way would be to use jQuery to perform the AJAX calls and to use JSON to format the data.

    0

    Like @HaukurHaf already said, you need client side script. If you don't like Javascript, you can use use it just to detect change and send an ajax request to server where you could return a partial view .

    $.ajax({ url: "GetTownsByCountry", context: $("#country").val() }).done(function() { // update you div here ! }); 

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.