javascript - How to refresh div after AJAX request in MVC? -
i'm not sure how refresh data after use ajax. here's have:
frontend:
@model tfu.model.db_user <div id="listtelnumbers"> @foreach (var item in model.db_user_phones) { <dl class="dl-horizontal"> <dt> @item.phone </dt> <dd> <button id="removebutton" class="btn btn-default" onclick="sendrequesttoremove('@item.user_id', '@item.phone')">usuń</button> </dd> </dl> } </div> script - fadeout works fine don't know should fadein. guess missing small part of code there. how can fadeout record removing instead list.
<script> function sendrequesttoremove(id, phone) { var data = { "user_id": id, "phone": phone } $.ajax({ url: '/user/removetelnumber', data: json.stringify(data), type: 'post', contenttype: 'application/json; charset=utf-8', error: function (err) { alert('error: ' + err.statustext); }, success: function (result) { $('#listtelnumbers').fadeout(800, function () { form.html('#listtelnumbers').fadein().delay(2000); }); }, async: true, processdata: false }); } </script> backend:
public bool removetelnumber(db_user_phones model) { var user = db.db_user_phones.first(x => x.user_id == model.user_id && x.phone == model.phone); db.db_user_phones.remove(user); db.savechanges(); return true; }
firstly, loop generating duplicating invalid html because of duplicate id attributes. , should not polluting markup behavior - use unobtrusive javascript. change html remove id attribute, add class name selection , add data-* attributes values posted
@foreach (var item in model.db_user_phones) { <dl class="dl-horizontal"> <dt>@item.phone</dt> <dd><button class="btn btn-default delete" data-id="@item.user_id" data-phone="@item.phone">usuń</button></dd> </dl> } then change script to
var url = '@url.action("removetelnumber", "user")'; // use url.action() $('.delete').click(function() { var container = $(this).closest('dl'); var data = { user_id: $(this).data('id'), phone: $(this).data('phone') }; $.post(url, data, function(response) { if (response) { // fadeout, remove container.fadeout(800, function() { $(this).remove(); }) } else { // oops - display error message? } }).fail(function() { // oops }); }); and finally, change action method return jsonresult indicating success or otherwise
[httppost] public jsonresult removetelnumber(db_user_phones model) { var user = db.db_user_phones.first(x => x.user_id == model.user_id && x.phone == model.phone); db.db_user_phones.remove(user); db.savechanges(); return json(true); // or if went wrong, return json(null); } i recommend rename classes , properties follow conventional naming practices - userphone, not db_user_phones, userid, not user_id etc.
Comments
Post a Comment