Nick Zulanas Nick Zulanas - 23 days ago 16
Javascript Question

Reload div fires constantly without event MVC

I am working on a project in Visual studio using MVC. I am trying to reload a div after a btn is clicked and data has been posted to the controller dynamically. I use an Ajax post and return a JSONresult. The code for posting looks like this:

<div id = "DelUser">
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Dform" }))
{
<label> Select User(s) to Delete: </label>

@Html.ListBox("Users", ViewBag.Users as MultiSelectList,
new { @class = "chzn-select", @style = "width:250px; height:350 px" })

}
<button class="btn btn-primary dropdown-toggle" id="Button1" type="button" onclick="DeleteUsers()"> Delete Selected </button>
</div>
<script>

function DeleteUsers() {
var myList = []
$("#Users > option:selected").each(function () {
myList.push($(this).val());
});


jQuery.ajax({
type: 'post',
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: 'DeleteU',
data: JSON.stringify(myList),
success: function (data) {
$('#msgbx2').html(data.msg);
//here I am trying to refresh the div after the post but it fires every second
$('#DelUser').html('/Home/DeleteUser');

},
failure: function (errMsg) {
$('#msgbx2').html(data.msg);
}

});

return false;

}




The name of the controller is DeleteUser and the JSONresult controller is DeleteU.

I am trying to do this so that the dropdownlist updates after I delete the selected users. If there is another way to dynamically update this div, any information on that would be good to know too. Thank you in advance.

Here are the Controllers as well:

[HttpGet]
public ActionResult DeleteUser()
{
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] user in users)
{
u.Add((string)user[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
return View();
}
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{

bool good = false;
if (Users != null)
{
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
good = data.insert_update_delete_DB(ins);
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] usera in users)
{
u.Add((string)usera[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
if (good == true)
{
ViewBag.error = "You have successfully deleted user";
}
else
{
ViewBag.error = "There was an issue removing user";
}

}

return Json(new { msg = "You have Successfully deleted Users " });
}

return Json(new { msg = "the passwords entered do not match" });
}


This is just a section of my main page that has other action functions/controllers in it which is why i did not originally post the controllers

Answer

You can simply update the existing listbox by removing the currently selected items. Start by removing onclick="DeleteUsers() from the button and use Unobtrusive JavaScript. Since you do not appear to have a POST method for DeleteUser() or a submit button, you may as well also replace @using (Html.BeginForm(...)) with just <form> elements. The script will then be

$('#Button1').click(function () {
    var users = [];
    var selected = $('#Users option:selected'); // store the selected users
    $.each(selected, function (index, item) {
        users.push($(this).val());
    })
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: '@Url.Action("DeleteU", "yourControllerName")', // always use Url.Action to generate your url's
        data: { users: users },
        traditional: true,
        success: function () {
            // remove the currently selected options
            selected.remove();
        }
    });
})
Comments