I'm not sure how to refresh data after I use AJAX. Here's what I already 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 but I don't know what should I fadeIn
. So I guess is missing a small part of code there. Also how can I fadeOut
only the record which I currently removing instead all 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, your loop is generating duplicating invalid html because of the duplicate id
attributes. And you should not be polluting your markup with behavior - use Unobtrusive JavaScript. Change the html to remove the id
attribute, add a class
name for selection and add data-*
attributes for the values to be 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 the script to
var url = '@Url.Action("RemoveTelNumber", "User")'; // always 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, then remove
container.fadeOut(800, function() { $(this).remove(); })
} else {
// Oops - display an error message?
}
}).fail(function() {
// Oops
});
});
And finally, change the action method to return a 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 something went wrong, return Json(null);
}
I also recommend you rename you classes and properties to follow conventional naming practices - UserPhone
, not DB_USER_PHONES
, UserId
, not USER_ID
etc.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments