Hi zeeshanpas,
In order to remove the Items from first ListBox, inside the foreach loop in the you need to find the option using the Value and remove it.
Refer below example.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Model
public class CategoryModel
{
public int[] SelectCategory { get; set; }
public int[] SelectedItems { get; set; }
public List<SelectListItem> Categories { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
NorthwindEntities entities = new NorthwindEntities();
List<Category> categories = entities.Categories.ToList();
CategoryModel category = new CategoryModel();
category.Categories = categories.Select(x => new SelectListItem
{
Text = x.CategoryName,
Value = x.CategoryID.ToString()
}).ToList();
return View(category);
}
public JsonResult GetCategories()
{
// Get the List from database.
List<SelectListItem> categories = new List<SelectListItem>();
categories.Add(new SelectListItem { Text = "Condiments", Value = "2" });
categories.Add(new SelectListItem { Text = "Grains/Cereals", Value = "5" });
return Json(categories, JsonRequestBehavior.AllowGet);
}
}
View
@model ListBox_Item_Remove.Models.CategoryModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "GET",
url: "@Url.Action("GetCategories", "Home")",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != undefined && data.length > 0) {
$.each(data, function (i, item) {
$('#ddlSelectedCategories').append('<option value=' + item.Value + '>' + item.Text + '</option>');
// Remove items from 1st ListBox.
$("#ddlCategories option[value='" + item.Value + "']").remove();
});
}
},
error: function (data) {
alert(data.responseText);
}
});
});
</script>
</head>
<body>
@Html.ListBoxFor(m => m.SelectCategory, Model.Categories, new { @id = "ddlCategories", @size = 10 })
@Html.ListBoxFor(m => m.SelectedItems, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), new { @id = "ddlSelectedCategories", @size = 10 })
</body>
</html>
Screenshot
In this example i am calling jQuery Ajax on page load. So you need to call in the edit event.