javascript - how to call an ajax function with dynamic ID's- MVC -


i try update dropdownlist selected item in dropdownlist . page contain option multiple dropdownlist same data

@model list<cimenacityproject.models.timescreening>  @{ viewbag.title = "create"; int? numberofnewtimescreening = viewbag.number; if (!numberofnewtimescreening.hasvalue) {     numberofnewtimescreening = 1; }  (int = 0; < numberofnewtimescreening; i++) {  }  var selectmovieid = (selectlist)viewbag.movieid; var selecthomecinemaid = (selectlist)viewbag.homecinemaid; }  <h2>create</h2>   @using (html.beginform("create", "timescreening", formmethod.post)) {      @html.antiforgerytoken()  <div class="form-horizontal">     <h4>timescreening</h4>     <hr />     @html.validationsummary(true)     <table>         <tr>             <th>                 @html.label("showtime", new { @class = "control-label col-md-2" })             </th>             <th>                 @html.label("theatres", new { @class = "control-label col-md-2" })             </th>             <th>                 @html.label("date", new { @class = "control-label col-md-2" })             </th>             <th>                 @html.label("price", new { @class = "control-label col-md-2" })             </th>             <th>                 @html.label("is displayed", new { @class = "control-label col-md-2" })             </th>             <th>                 <div class="col-md-offset-2 col-md-10">                     <input type="submit" value="create" class="btn btn-default" />                 </div>             </th>         </tr>          @for (int = 0; < numberofnewtimescreening.value; i++)         {             string homecinemaid = "["+i + "].movietheaters.homecinemaid".tostring();             string theatresid = "["+ + "].theatresid".tostring();                 <tr>                 <td>                     <div class="col-sm-8">                         <br />                         @html.dropdownlistfor(model => model[i].movieshowtime.single().movieid, selectmovieid, "select movie")                         <br /><br />                         @html.dropdownlistfor(model => model[i].movieshowtimeid, enumerable.empty<selectlistitem>(), "--loading value--")                         @html.validationmessagefor(model => model[i].movieshowtimeid)                     </div>                 </td>                 <td>                     <div class="col-sm-8">                         <br />                         @html.dropdownlistfor(model => model[i].movietheaters.homecinemaid, selecthomecinemaid, "select home cinema",                  new { id = homecinemaid.tostring(), name = homecinemaid.tostring() })                          <br /><br />                          @html.dropdownlistfor(model => model[i].theatresid, enumerable.empty<selectlistitem>(), "--loading value--",                         new {id=theatresid.tostring(), name = theatresid.tostring()})                         @html.validationmessagefor(model => model[i].theatresid)                     </div>                 </td>                 <td>                     <div class="col-sm-8">                         <br />                         @html.editorfor(model => model[i].date)                         @html.validationmessagefor(model => model[i].date)                     </div>                 </td>                 <td>                     <div class="col-sm-8">                         <br />                         @html.editorfor(model => model[i].price)                         @html.validationmessagefor(model => model[i].price)                     </div>                 </td>                 <td>                     <div class="col-sm-8">                         <br />                         @html.editorfor(model => model[i].isdisplayed)                         @html.validationmessagefor(model => model[i].isdisplayed)                     </div>                 </td>                 <td></td>             </tr>         }     </table> </div> } 

as see page number , loop duplicate data . when loop start gave dynamic id dropdownlist

model[i].theatresid  

when user select homecinema ajax have start , loading theatres connect home cinema .

the code here contain founction homecinema , movie . last code convert json datetime.

ajax code :

<script type="text/javascript">   //function homecinema.      $(function () {         $('@homecinemaid.tostring()').change(function () {             alert("ok1")             $.ajax({                 type: "post",                 url: '@url.action("gettheatres","timescreening")',                 data: { cinemaid: $('@homecinemaid.tostring()').val() },                 success: function (data) {                     $(@theatresid.tostring()).html('');                     $.each(data, function (id, option) {                         $(@theatresid.tostring()).append($('<option></option>').val(option.id).html(option.name));                     });                 },                 error: function (xhr, ajaxoptions, throwneror) {                     alert("error loading theatres");                 }             });         });    });       $(function () {         $('#'+j + '.movieid').change(function () {             $.ajax({                 type: "post",                 url: '@url.action("getshowtime", "timescreening")',                 data: { movieid: $('#' + j + '.movieid').val() },                 datatype: 'json',                 success: function (data) {                     $('#' + j + '.movieshowtimeid').html('');                     $.each(data, function (id, option) {                         var name = datetimeconverter(option.name)                         $('#' + j + '.movieshowtimeid').append($('<option></option>').val(option.id).html(name));                     });                  },                 error: function (xhr, ajaxoptions, throwneror) {                     alert("false" + xhr + "..." + ajaxoptions + "... " + throwneror);                 }             });         });     });   // start datetime converters function dateconverter(date) {     var aux = null;     if (date != null) {         aux = date.substring(6);         aux = aux.substring(0, aux.indexof(')'));     }      return aux != null ? getisodate(new date(parseint(aux))) : ""; }  function datetimeconverter(date) {     var aux = null;     if (date != null) {         aux = date.substring(6);         aux = aux.substring(0, aux.indexof(')'));     }     return aux != null ? getisodatetime(new date(parseint(aux))) : ""; }  function getisodate(d) {     // padding function     var s = function (a, b) { return (1e15 + + "").slice(-b) };      // default date parameter     if (typeof d === 'undefined') {         d = new date();     };      // return iso datetime     return zeropad(d.getdate(), 2) + '/' +     zeropad(s(d.getmonth() + 1, 2), 2) + '/' +     zeropad(d.getfullyear(), 4); }  function getisodatetime(d) {     // padding function     var s = function (a, b) { return (1e15 + + "").slice(-b) };      // default date parameter     if (typeof d === 'undefined') {         d = new date();     };      // return iso datetime     return zeropad(d.gethours(), 2) + ":" +     zeropad(d.getminutes(), 2) + ":" +     zeropad(d.getseconds(), 2); }  function zeropad(num, places) {     var 0 = places - num.tostring().length + 1;     return array(+(zero > 0 && zero)).join("0") + num; } // end datetime converters   </script>     }     } 

code :

        public actionresult gettheatres(int? cinemaid)     {         var data = (from d in db.theaters                     d.homecinemaid == cinemaid                     select new                     {                         id = d.movietheatersid,                         name = d.theatersname                     }).tolist();          return json(data,jsonrequestbehavior.allowget);     }      public jsonresult getshowtime(int? movieid)     {          var data = (from m in db.movieshowtimes                     m.movieid == movieid                     select new                     {                         id = m.movieshowtimeid,                         name = m.showtime                     }).tolist();          return json(data, jsonrequestbehavior.allowget);     } 

after controller list user make , add db.

controller:

    // post: /timescreening/create     [httppost]     [validateantiforgerytoken]     public actionresult create([bind(include = "timescreeningid,movieshowtimeid,theatresid,date,price,isdisplayed")] list<timescreening> timescreening)     {         int check = 0;         foreach (var timescreening in timescreening)         {             if (modelstate.isvalid)             {                 db.timescreening.add(timescreening);                 check = db.savechanges();              }         }         if (check== 1)         {             return redirecttoaction("index");         }         return view("create", timescreening);        } 

when work 1 element (no loop , static id) work perfect how can make work multiple , dynamic id's?

ziv, instead of attaching change event handler id selector, class instead. , every dropdown want event handled way coded, add specific class.

don't define id element in dropdowns @ all.

example:

<select class='mydropdown' ...>  </select>  <select class='mydropdown' ...> </select>  **jquery**: $(".mydropdown").change(function(){     // code here }); 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -