Send list of items in MVC - javascript

this is my item
public class RequestViewModel
{
public long FeederId { set; get; }
public int A { set; get; }
public int B { set; get; }
public int C { set; get; }
public int Remain { set; get; }
}
and this is my Add model that i want to send from my form to my Controller
public class RequestAddListViewModel
{
public List<SuppliantRequestFeederAddViewModel> SuppliantRequestFeederAddViewModels { set; get; }
public List<SelectListItem> FeederSelectListItems { set; get; }
public long NodeId { set; get; }
}
first time my form load i have One item i have a button when i click on it my first row clone and append to my form for example now i have 8 item on my form, i can delete each item on client side. if i didn't delete any item and submit form there no problem.
My problem is when delete one of item for example second one when deleted and then submit my form there is no item on my controller. nothing send to Controller.
View
#for (int index = 0; index < Model.RequestAddListViewModel.Count; index++)
{
var req = Model.RequestAddListViewModel[index];
<tr class="requestrow">
<td>
#Html.DropDownListFor(p => p.req[index].FeederId, Model.FeederSelectListItems, new { #class = "form-control" })
</td>
<td>
#Html.TextBoxFor(p => p.req[index].A, new { #class = "form-control" })
</td>
<td>
#Html.TextBoxFor(p => p.req[index].B, new { #class = "form-control" })
</td>
<td>
#Html.TextBoxFor(p => p.req[index].C, new { #class = "form-control" })
</td>
<td>
<button type="button" class="btn btn-primary btn-icon btn-rounded newfeeder"><i class="icon-plus2"></i></button>
</td>
</tr>
}
and my jQuery script (Edited):
var inputCount=0;
$(document).on('click', '.newfeeder', function () {
inputCount++;
var tr = $(this).closest("tr").clone();
tr.find("input").val(0);
tr.find("button").removeClass("btn-primary").addClass("btn-danger").removeClass("newfeeder").addClass("deleterow");
tr.find("button i").removeClass("icon-plus2").addClass("icon-trash");
tr.find("input,select").each(function () {
$(this).attr({
'name': function (_, name) { return name.toString().replace('0', inputCount) },
'id': function (_, id) { return id.toString().replace('0', inputCount) }
});
});
$(this).closest("tr").after(tr);
});
$(document).on('click', '.deleterow', function() {
$(this).closest("tr").remove();
});

finally i found my solution after add or delete new item to my form
i call this function ReCreateIndex()
function ReCreateIndex(container) {
$(container).each(function (index, obj) {
$("input,select", $(this)).each(function () {
if ($(this).attr("name")) {
var name = $(this).attr("name").replace($(this).attr("name").replace(/[^0-9]/gi, ''), index);
$(this).attr("name", name);
}
if ($(this).attr("id")) {
var id = $(this).attr("id").replace($(this).attr("id").replace(/[^0-9]/gi, ''), index);
$(this).attr("id", id);
}
});
});
}
it means that after any change on items,index of items recreated.

Related

Return Null in jQuery method for return subgroup

I have 2 method to get state and city from one table :
Model:
public string Title { get; set; }
public long? ParentId { get; set; }
public bool IsDeleted { get; set; }
public bool IsActive { get; set; }
and this is its view model
public string Title { get; set; }
public long LocationId { get; set; }
I have 2 method to get city and state .
and with first I choose first to show first city of ID:
var state = await _packageService.GetStateForUserInfo();
ViewData["State"] = state;
var firstLocationId = state.First().LocationId;
var city = await _packageService.GetCityForUserInfo(firstLocationId);
ViewData["City"] = city;
I user from view model. because when I use from select list, it returns null!
so after all on view this my select tag:
<label class="w-100 d-flex align-items-center" for="">
<label> State </label>
<select asp-for="LocationId" asp-items="(#ViewData["State"] as IEnumerable<SelectListItem>)" id="Location_Id" class="form-control">
<span asp-validation-for="LocationId"></span>
#foreach (var item in ViewBag.state)
{
<option value="#item.LocationId">#item.Title</option>
}
</select>
<label> City </label>
<select asp-for="LocationId" asp-items="(#ViewData["city"] as IEnumerable<SelectListItem>)" id="SubLocation_Id" class="form-control ">
<span asp-validation-for="LocationId"></span>
#foreach (var item in ViewBag.city)
{
<option value="#item.LocationId && #item.Title==Title">#item.Title</option>
}
</select>
</label>
and this is my jQuery :but it does not return Sub Locations( city) and does not save Id( I mean in location table field that :
ParentId == locationId
#section scripts
{
<script>
$("#Location_Id").change(function() {
$("#SubLocation_Id").empty();
$.getJSON("/UserPanel/UserInfo/GetSubGroup/" + $("Location_Id:selected").val(),
function(data) {
$.each(data,
function() {
$("#SubLocation_Id").append('<option value=' + this.value + '>' + this.text + '</option>');
});
});
});
</script>
}
Update:
this is my get and post method:
[HttpGet("userInfo/first-start-userInfo/{packageId}")]
public async Task<IActionResult> FirstStartUserInfo(long packageId,UserPanelMenu menu=UserPanelMenu.Packages )
{
if (packageId <= 0) return RedirectToAction("NotFound", "Home");
var userId = User.GetCurrentUserId();
if (!await _packageService.IsPackagePurchasedByUser(userId, packageId)) return RedirectToAction("NotFound", "Home");
var state = await _packageService.GetStateForUserInfo();
ViewData["State"] = state;
var firstLocationId = state.First().LocationId;
var city = await _packageService.GetCityForUserInfo(firstLocationId);
ViewData["City"] = city;
return View();
}
[HttpPost("userInfo/first-start-userInfo/{packageId}")]
public async Task<IActionResult> FirstStartUserInfo(CreateFirstStartUserInfoViewModel firstStartUserInfo )
{
var userId = User.GetCurrentUserId();
//if (!ModelState.IsValid) return View(firstStartUserInfo);
var res = await _packageService.CreateFirstStartUserInfoByUser(firstStartUserInfo, userId);
return View(firstStartUserInfo);
}
I fill its properties on service :
......
EditFirstStartUserInfoViewModel editFirstStartUserInfo = new EditFirstStartUserInfoViewModel()
{
PackageId = firstStartUserInfo.PackageId,
Address = firstStartUserInfo.Address,
DayOfBirth = firstStartUserInfo.DayOfBirth,
Goal = firstStartUserInfo.Goal,
Job = firstStartUserInfo.Job,
Marriage = firstStartUserInfo.Marriage,
MonthOfBirth = firstStartUserInfo.MonthOfBirth,
Sex = firstStartUserInfo.Sex,
UserPackageId = userPackageId,
UserInfoId = await _packageRepository.GetUserInfoIdByUserPackageIdAndUserInfoSituation(userPackageId, i),
YearOfBirth = firstStartUserInfo.YearOfBirth,
LocationId = firstStartUserInfo.LocationId == 0 ? null : firstStartUserInfo.LocationId
Update2:
Method to get city:
public async Task<IActionResult> GetSubGroup(long id)
{
var city =await _packageService.GetCityForUserInfo(id);
return Json(city);
}
I tested your code snippet in my side and I'm afraid the issue comes from $("Location_Id:selected").val(), this line-code will bring me undefined so your ajax get request may send an error data to the server. I used $("#Location_Id option:selected").val() instead.
And here's my testing code -- Controller
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
ViewData["State"] = new List<State> {
new State{ Title="state1_part1",LocationId=1},
new State{ Title="state1_part2",LocationId=2},
new State{ Title="state1_part3",LocationId=3},
new State{ Title="state1_part4",LocationId=4}
};
ViewData["City"] = new List<City> {
new City{ Title="city3",SubLocation_Id=2,LocationId=3},
new City{ Title="city4",SubLocation_Id=2,LocationId=4}
};
return View();
}
public JsonResult getCity(string id) {
if (id == "1")
{
var citys = new List<City> {
new City{ Title="city1",SubLocation_Id=1,LocationId=1},
new City{ Title="city2",SubLocation_Id=1,LocationId=2}
};
return Json(citys);
}
else {
var citys = new List<City> {
new City{ Title="city5",SubLocation_Id=3,LocationId=5},
new City{ Title="city6",SubLocation_Id=3,LocationId=6}
};
return Json(citys);
}
}
[HttpPost]
public IActionResult savedata(HomeModelView hmv) {
return View();
}
[HttpPost]
public IActionResult savedata2(TestViewModel tmv)
{
return View();
}
}
}
View page:
#model WebApplication1.Models.HomeModelView
#{
ViewData["Title"] = "Home Page";
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div>
<form asp-controller="Home" asp-action="savedata" method="post">
<label class="w-100 d-flex align-items-center" for="">
<label> State </label>
<select asp-for="#Model.State.LocationId" asp-items="(#ViewData["State"] as IEnumerable<SelectListItem>)" id="Location_Id" class="form-control">
<span asp-validation-for="#Model.State.LocationId"></span>
#foreach (var item in ViewBag.state)
{
<option value="#item.LocationId">#item.Title</option>
}
</select>
<label> City </label>
<select asp-for="#Model.City.LocationId" asp-items="(#ViewData["city"] as IEnumerable<SelectListItem>)" id="SubLocation_Id" class="form-control ">
<span asp-validation-for="#Model.City.LocationId"></span>
#foreach (var item in ViewBag.city)
{
<option value="#item.LocationId && #item.Title==Title">#item.Title</option>
}
</select>
</label>
<button type="submit">submit</button>
</form>
<button id="test">test</button>
</div>
<script>
$("#Location_Id").change(function () {
$("#SubLocation_Id").empty();
console.log($("Location_Id:selected").val());
var selectedid = $("#Location_Id option:selected").val();
$.getJSON("https://localhost:44386/home/getCity/" + selectedid,
function (data) {
console.log(data[0].title);
$.each(data,
function () {
$("#SubLocation_Id").append('<option value=' + this.locationId + '>' + this.title + '</option>');
});
});
});
$("#test").click(function () {
//write the logic to obtain the title and localtion id and send them to the server
var Title = "test_title";
var LocationId = 1233;
$.ajax({
url: "https://localhost:44386/home/savedata2/",
type: "POST",
data: {
Title: Title,
LocationId: LocationId
},
success: function (data) {
alert(data);
}
});
});
</script>
viewmodel:
namespace WebApplication1.Models
{
public class TestViewModel
{
public string Title { get; set; }
public long LocationId { get; set; }
}
}
Solved this problem.
first for JQUERY I had to add option as Tiny Wang " said to show city :
$("#Location_Id option:selected").val()
and for solve problem Get locationId of city , I should insert Asp-for just for city not state:
<label class="w-100 d-flex align-items-center" for="">
<label> state </label>
<select id="Location_Id" class="form-control">
#if (state.Any())
{
#foreach (var item in state )
{
<option value="#item.LocationId">#item.Title</option>
}
}
</select>
<span asp-validation-for="LocationId"></span>
<label> City </label>
<select asp-for="LocationId" id="SubLocation_Id" class="form-control ">
#foreach (var item in city)
{
<option value="#item.LocationId ">#item.Title</option>
}
</select>
<span asp-validation-for="LocationId"></span>
</label>

Pass Value[S] of multiple checkbox to Controller MVC | AJAX

Im loading contents dynamically to table as you see i have an input and i have two Checkbox:
$.ajax({
type: "GET",
url: "/User/GetCustomerContactInfo",
data: { ids: items },
traditional: true,
dataType: 'json',
success: function (values) {
for (var i = 0; i < values.length; i++) {
value = values[i]
if (value != null) {
holderHTML += '<tr id="row' + value.CustomerNo + '">';
holderHTML += '<td><input id="NameOfCompany" name="[' + i + '].NameOfCompany" value="' + value.NameOfCompany + '" /></td>';
holderHTML += '<td><input id="checkboxCustom1" type="checkbox" name="[' + i + '].RightsCode" value="Åbne ordrer"/>
<input id="checkboxCustom1" type="checkbox" name="[' + i + '].RightsCode" value="Lukkede ordrer"/></td>
holderHTML += '</tr>';
}
}
$('#output').append(holderHTML);
},
error: function () {
console.log('something went wrong - debug it!');
}
})
And HTML Output will be like:
<form id="CustomerNEmployeeForm">
<table>
<tbody id="output">
<tr id="row10883">
<td>
<input type="text" id="NameOfCompany" name="[0].NameOfCompany" value="Center">
</td>
<td>
<input id="checkboxCustom1" type="checkbox" name="[0].RightsCode" value="Åbne ordrer">
<input id="checkboxCustom1" type="checkbox" name="[0].RightsCode" value="Fakturerede ordrer">
</td>
</tr>
</tbody>
</table>
</form>
<button class="btncreateusers" id="createusersJS" type="button" onclick="CreateCustomerNEmployees();">Create</button>
 And than i want to get value of checkbox and pass to controller by Serialize form, but when form being Serialized, it will pass only value of first Checkbox:
function CreateCustomerNEmployees() {
var formdata = $("#CustomerNEmployeeForm").serializeArray();
console.log(formdata);
$.ajax({
"url": '#Url.Action("CreateCustomers", "User")',
"method": "POST",
"data": formdata ,
"dataType": "json",
complete: function () {
}
});
}
Output console.log(formdata):
0: {name: "[0].NameOfCompany", value: "Center"}
1: {name: "[0].RightsCode", value: "Åbne ordrer"}
2: {name: "[0].RightsCode", value: "Lukkede ordrer"}
Model:
public class CreateCustomers
{
public string NameOfCompany { get; set; }
public string RightsCode { get; set; }
}
Controller:
[HttpPost]
public JsonResult CreateCustomers(List<CreateCustomers> model)
{
if (model == null)
{
model = new List<CreateCustomers>();
}
var resultsOne = new List<Users>();
var resultsTwo = new List<Rettigheder>();
foreach (var item in model)
{
var UsersInsert = new Users
{
CompanyName = item.NameOfCompany,
//other property
};
var RettighederInsert = new Rettigheder
{
//other property
Rettighedskode = item.RightsCode
};
resultsOne.Add(UsersInsert);
db.Users.Add(UsersInsert);
resultsTwo.Add(RettighederInsert);
db.Rettigheder.Add(RettighederInsert);
}
db.SaveChanges();
return Json(model, JsonRequestBehavior.AllowGet);
}
Debug Output:
https://i.imgur.com/DT6TYd4.jpg
The CreateCustomers Model has specified RightsCode as a single string.
public class CreateCustomers
{
public string NameOfCompany { get; set; }
public string RightsCode { get; set; }
}
The MVC model binding in this case binds the first match only.
If you want all RightsCode checkboxes bound you need to change RightsCode to a string array.
public class CreateCustomers
{
public string NameOfCompany { get; set; }
public string[] RightsCode { get; set; }
}
Unrelated but good practice -
html tag id values should be unique. Names can be duplicated but id values that are not unique can cause problems with css/js selectors.

How to get value of single input field and sending with each products to database

I have page, where i add one or many products (this part is working) and its adding products including (Product Name, Serial number, Qty) to database. As also you see in screenshots i have single input field Customer Name which i want get value of Customer Name input feild and sending with each products to database.
Example when data inserted into database:
Customer Name | Product Name | Serial number | Qty
Stackoverflow A 1234 1
Stackoverflow B 4567 2
But, right now look like this in my database when its inserting data :
Customer Name | Product Name | Serial number | Qty
null A 1234 1
null B 4567 2
To be honest i dont know how can i sending value of Customer Name input field with each products when its trying insert data into database. Can anyone please help me or point me into the right direction! Thanks in advance :)
Controller:
[HttpPost]
public JsonResult ProcessCreateRMA(CreateRMAVM vm)
{
using (var namespace = new namespace())
{
if (vm.vares == null)
{
vm.vares = new List<CreateRMAVM.vare>();
}
foreach (var item in vm.vares)
{
var rmainsert = new RMA_History
{
//CustomerName = item.CustomerName,
ProductName = item.ProductName,
Serialnumber = item.Serialnumber,
Qty = item.Qty,
};
db.RMA_History.Add(rmainsert);
}
db.SaveChanges();
}
return Json(vm, JsonRequestBehavior.AllowGet);
}
JavaScript:
<script>
$(document).ready(function () {
//Add input field
var i = 0;
$("#add").click(function (e) {
i++;
e.preventDefault();
$("#tbhold").append('<tr id="row' + i + '"><td><div><input type="text" name="vares[' + i + '].ProductName" id=' + i + ' /></div></td><td><div><input type="text" name="vares[' + i + '].SerialNumber" id=' + i + '/></div></td><td><div style="padding:0" class="col-md-12"><input id="Qty" name="vares[' + i + '].Qty"/></div></td><td><button type="button" class="btn btn-danger btn_remove" id="' + i + '" name="remove"><i class="fa fa-minus-circle" aria-hidden="true"></i>Remove</button></td></tr>');
});
//Remove input field
$(document).on('click', '.btn_remove', function () {
var button_id = $(this).attr("id");
$("#row" + button_id + '').remove();
});
//Save to db by click
$("#submit").click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '#Url.Action("ProcessCreateRMA", "User")',
dataType: 'json',
data: ($('#add_rma').serialize()),
success: function (result) {
console.log(result);
},
error: function () {
console.log('something went wrong - debug it!');
}
});
});
});
</script>
View:
<label>Customer Name</label>
<input type="text" name="CustomerName" id="CustomerName">
<form name="add_rma" id="add_rma">
<table id='tbhold' class="table">
<thead>
<tr>
<th>Product Name </th>
<th>Serial number</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div>
<input type="text" name="vares[0].ProductName" id="ProductName" />
</div>
</td>
<td>
<div>
<input type="text" name="vares[0].Serialnumber" id="Serialnumber" />
</div>
</td>
<td>
<div>
<input name="vares[0].Qty" id="Qty"/>
</div>
</td>
<td>
<button type="button" name="add" id="add">Add more</button>
</td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
ViewModel:
public class CreateRMAVM
{
public List<vare> vares { get; set; }
public class vare
{
public vare()
{
}
public vare(/*string CustomerName*/ string ProductName, string SerialNumber, string Qty)
{
}
//public string CustomerName { get; set; }
public string ProductName { get; set; }
public string SerialNumber { get; set; }
public string Qty { get; set; }
}
}
I have updated your code to work. If you are using a datagrid, I might recommend you use one of the numerous ones out there and not try to rebuild it yourself. jqGrid (http://www.trirand.com/blog/) is one that's popular
Leave the CompanyName inside your form
Update your model as such. I've include the Customer in CreateRMAVM and in vare
public class CreateRMAVM
{
public List<vare> vares { get; set; }
public string CustomerName { get; set; }
public class vare
{
public vare()
{
}
public vare(/*string CustomerName*/ string ProductName, string SerialNumber, string Qty)
{
}
public string CustomerName { get; set; }
public string ProductName { get; set; }
public string SerialNumber { get; set; }
public string Qty { get; set; }
}
}
Update your controller as such. CustomerName will come populated in CreateRMAVM, and then there's a line of code to copy into the vare lists
[HttpPost]
public JsonResult Create(CreateRMAVM vm)
{
try
{
if (vm.CustomerName != null && vm.vares != null)
{
vm.vares.Select(c => { c.CustomerName = vm.CustomerName; return c;
}).ToList();
}
<input type="text" name="CustomerName" id="CustomerName">
is not within your form definition. Move this into the form

Client Side validation In MVC with Entity framework

I am working on a form in which i have to validate my user inputs (i.e, textbox and dropdownlist). in this i have used both MVC architecture as well as entity framework.
In this form i have to make a validation that the input in textboxt should not be blank and the dropdownlist should also contain a valid option
the form is generated using razor html syntax
VIEW
<form method="post">
<table>
<tr>
<td>
#Html.Label(" Cartidge Number ") <span style="color:red">*</span>
</td>
<td>
#Html.TextBoxFor(model => model.CartridgeNumber, "", new { #id = "txtNumber"})
#Html.ValidationMessageFor(model => model.Brand)
</td>
</tr>
<tr>
<td>
#Html.Label(" Brand ") <span style="color:red">*</span>
</td>
<td>
#Html.DropDownListFor(model => model.Brand, ViewBag.BrandId as SelectList,"Please Select", new { #id = "ddlBrands" })
#Html.ValidationMessageFor(model => model.Brand)
</td>
</tr>
<tr>
Model
Modelname is CartridgeModel which is generated using entity framework's database first approach
namespace MultiInfoMediaCloudSolution.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class CartridgeModel
{
[Display(Name = "Cartridge Number: ")]
[Required(ErrorMessage = " Please Enter Cartridge Number ")]
public string CartridgeNumber { get; set; }
[Display(Name = "Brand: ")]
[Required(ErrorMessage = " Please Select Brand ")]
public string Brand { get; set; }
public string CartridgeKeywords { get; set; }
public Nullable<bool> IsActive { get; set; }
public Nullable<short> CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public Nullable<short> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual Brand BrandName { get; set; }
}
}
Controller
{
// check if the user has selected to edit the item or not.
if (userAction == "Edit")
{
var _Printer = (from c in _multiInfoMediaEntities.PrinterModels
where c.PrinterModelNo.Equals(PrinterModelNo)
select c).First();
//to store PrinterModelNo
string printerNumberTemp = _Printer.PrinterModelNo;
TempData["PrinterModelNo"] = printerNumberTemp;
TempData["IsActive"] = _Printer.IsActive;
TempData["userAction"] = "Edit";
return View(_Printer);
}
else
{
return View();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
I am using a javaScript to validate my form which is unusually not giving me any result as per my expections,
the javascript is as follow
JavaScript
//................................Go Function is user for the Validation in all the List........................
function GO() {
var ddl = document.getElementById("dllFilter");
var brands = document.getElementById("ddlBrands");
if (ddl.options[ddl.selectedIndex].text == "Please Select") {
alert("Please select search field");
}
if(brands.innerText == "Please Select")
{
alert("Please select brand")
}
}
//................................
//.......................Clear function is Used for Clearing the textbox Value from all the List........................
function Clear() {
document.getElementById('txtSearch').value = 'Enter Value';
//ViewData["Selected"] = "Please Select";
}
//......................................................................................................
So, can anyone help me or guide me in solving this problem. ?
If you require simple client side validation, you can use the "required" attribute
<input type="text" required /> or in your case #Html.TextBoxFor(model => model.CartridgeNumber, "", new { #id = "txtNumber", required = "required"})
As for the dropdown you can use the same required attribute but for it to work the first 'option' child element must have a blank string for value <option value="">Please select an option</option>

What's wrong with this jQuery code for multiple listboxes?

I can't get the following jQuery code to work (it doesn't transfer selected items between listboxes) in an MVC 5 app:
<script>
$(function () {
$("add").click(function () {
$("#listBoxAvail > option:selected").each(function () {
$(this).remove().appendTo("#listBoxSel");
});
});
$("remove").click(function () {
$("#listBoxSel > option:selected").each(function () {
$(this).remove().appendTo("#listBoxAvail");
});
});
});
</script>
The rest of the markup with the listboxes is:
#using (Html.BeginForm())
{
#Html.ListBoxFor(m => m.SelectedAttributes, Model.Attributes, new {id="listBoxAvail", SIZE = 5} )
<input type="submit" name="add"
id="add" value="MoveRight" />
<input type="submit" name="remove"
id="remove" value="MoveLeft" />
<input type="submit" name="remove-all" id="remove-all" value="RemAll" />
<input type="submit" name="select-all" id="select-all" value="SelAll" />
#Html.ListBoxFor(m => m.SelectedAttributes2, Model.SelectedItems, new { id = "listBoxSel", SIZE = 5})
}
</div>
The ViewModel is:
public class OptInViewModel
{
public IEnumerable<string> SelectedAttributes { get; set; }
public IEnumerable<string> SelectedAttributes2 { get; set; }
public IEnumerable<SelectListItem> Attributes { get; set; }
public IEnumerable<SelectListItem> SelectedItems { get; set; }
}
And the controller is:
public ActionResult Index()
{
AttributeEntities db = new AttributeEntities();
List<SelectListItem> listSelectListItems = new List<SelectListItem>();
List<SelectListItem> listSelItems = new List<SelectListItem>();
foreach (var attributes in db.HarmonyAttributes)
{
SelectListItem selectList = new SelectListItem
{
Text = attributes.AttributeName,
Value = attributes.AtrributeLabel,
Selected = false
};
listSelectListItems.Add(selectList);
}
foreach (var sel in db.SelectedHarmonyAttributes)
{
SelectListItem selList = new SelectListItem
{
Text = sel.CustomLabel,
Value = sel.HarmonyAttribute_ID.ToString(),
Selected = false
};
listSelectListItems.Add(selList);
}
OptInViewModel viewModel = new OptInViewModel
{
Attributes = listSelectListItems,
SelectedItems = listSelItems
};
return View(viewModel);
}
}
I can't figure out why the JQuery script won't work. What am I doing wrong?
Looks like selector is wrong, you are trying to assign handler to element "add":
$("add")
instead of element with id "add"
$("#add")
Same for "remove" element.
I know I am years late, but it might help somebody else.
It's refreshing because you buttons are o type submit.
Change this :
<input type="submit" name="remove"
id="remove" value="MoveLeft" />
To this :
<input type="button" name="remove"
id="remove" value="MoveLeft" />

Categories