I have been working on this for a little while today and I am stumped. I am attempting to select a date using a date picker and take that date, populate a label with it and also take input from the user to add days to the selected date. The date picker works fine, I however cannot get the date to populate the label and I am not sure how to calculate say 6 days in advance with that date. The code to add the days is straight forward, I am not sure how to take the date and make it calculable.
Here is what I have so far:
View
#{
ViewBag.Title = "Index";
}
<link type="text/css" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<form id="calendarForm" action="~/Views/Calendar/Calendar.cshtml" method="post">
<h2>Calendar Application</h2>
<p>This application will display a the specified number of days <br /> the user inputs on a calendar.</p>
<br />
<h2>Select A Date</h2>
#model VanickCalendarApp.Models.Calendar
<!-- Date picker visible -->
<p>
<input type="text" id="Date" />
</p>
<!-- Takes the date from the picker and calculates it new date on button click-->
<script>
$('button').click(function () {
var datePickerSelected = $("#Date").datepicker("getDate");
var endDate = new Date();
var selDate = $('#Date').val();
var DaysToBeAdded = addDaysEntered;
endDate = (selDate + DaysToBeAdded);
});
</script>
#using (Html.BeginForm("Calculate Days", "Calendar", FormMethod.Post))
{
<h2>Enter The Number Of Days To Display</h2>
#Html.TextBoxFor(model => model.DaysToBeViewed)
<label id="dateSelected">"Date"</label>
<input type="button" value="Submit" onclick="daysAdded()" />
}
<!-- Create the date picker script -->
<script>
$(function () {
$('#Date').datepicker();
});
</script>
<!-- Creates an alert to test the values for debuging -->
<script>
document.getElementById('dateSelected').valueOf = dateSelected
alert.valueOf("Date");
</script>
</form>
Controller
using System.Web.Mvc;
using VanickCalendarApp.Models;
namespace VanickCalendarApp.Controllers
{
public class CalendarController : Controller
{
public string CalculateDays(string Date)
{
var oneDAY = 1000 * 60 * 60 * 24;
return Date;
}
//
// GET: /Calendar/
public ActionResult Calendar()
{
return View();
}
//
// GET: /Calendar/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Calendar/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Calendar/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Calendar/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /Calendar/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Calendar/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Calendar/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Model
using System;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
namespace VanickCalendarApp.Models
{
public class Calendar
{
//[DataType(DataType.Date)]
public string date { get; set; }
public int DaysToBeViewed { get; set; }
public DateTime newDate { get; set; }
}
}
Related
I have a functionality where I append a select html when a button is clicked using jQuery. I already have a select which uses a asp-item tag helper to fill it with my corresponding model. The platform I'm using is asp-net core 2.2 and I'm using a razor page for my page.
My question is how do I edit my jQuery so that when I clicked the button, the asp-item is already loaded into the select?
Here is my jQuery code:
$("#AddButton").click(function () {
tc = tc + 1;
$("#totalContacts").val(tc)
$(".addselection").append('<div> <select class="form-control" name="[' + (tc) + '].DriverID" asp-for="TripDrivers.DriverID" asp-items="Model.DriverList" > <option value = ""> Select a driver </option></select></div>')
});
and this is my OnGet to load the items
public IActionResult OnGet()
{
DriverList = _context.Drivers.Select(a =>
new SelectListItem
{
Value = a.ID.ToString(),
Text = a.FullName
}).ToList();
}
This is my first ever question, so please bear with me if there are any grammatical errors or missing information. I'll add them if necessary.
EDIT: Here is the design I'm trying to do.
Once the plus button is clicked. It should add a row of dropdownlist each with the option being loaded from the list on the OnGet method.
ANOTHER EDIT: As per user #itminus instructions, I've created a one sample page and a partial view to apply the code given below.
Here is what my FirstPage.cshtml looks like
#page
#model MasigasigTrackingSystem.Pages.TestingPages.FirstPageModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>FirstPage</title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script>
$("#AddButton").click(function () {
tc = tc + 1;
$("#totalContacts").val(tc)
$.ajax('?handler=DropdownList', {
method: "GET",
data: { tc: tc },
success: function (d) { $(".addselection").append(d); }
});
});
</script>
</head>
<body>
<button id="AddButton" class="btn" type="button">+</button>
#*<select asp-for="Mode" asp-items="Model.DropdownListViewModel.Drivers" class="form-control">
<option value="">Select a driver</option>
</select>*#
<div class="addselection">
<partial name="_SecondPage.cshtml" />
</div>
</body>
</html>
My FirstPageModel
namespace MasigasigTrackingSystem.Pages.TestingPages
{
public class FirstPageModel : PageModel
{
private readonly MasigasigTrackingSystem.Data.ApplicationDBContext _context;
public FirstPageModel(MasigasigTrackingSystem.Data.ApplicationDBContext context)
{
_context = context;
}
[BindProperty]
public Drivers Drivers { get; set; }
public List<SelectListItem> DriverList { get; set; }
[BindProperty]
public DropdownListViewModel DropdownListViewModel { get; set; }
public void OnGet()
{
DriverList = _context.Drivers.Select(a =>
new SelectListItem
{
Value = a.ID.ToString(),
Text = a.FullName
}).ToList();
DropdownListViewModel = new DropdownListViewModel();
DropdownListViewModel.Drivers = DriverList;
}
public IActionResult OnGetDropdownListAsync(int tc)
{
var list = _context.Drivers.Select(a => new SelectListItem
{
Value = a.ID.ToString(),
Text = a.FullName,
}).ToList(); // or filter by Where( ... tc...).ToList()
return Partial("/Pages/TestingPages/_SecondPage.cshtml", new DropdownListViewModel
{
Drivers = list,
ID = tc,
});
}
}
}
My partial _SecondPage
#using MasigasigTrackingSystem.Models
#model DropdownListViewModel
<div>
<select class="form-control dropdown" name="[#Model.ID].DriverID" asp-items="#Model.Drivers">
<option> Select a driver </option>
</select>
</div>
My DropdownlistViewModel
namespace MasigasigTrackingSystem.Models
{
public class DropdownListViewModel
{
public int ID { get; set; }
public IList<SelectListItem> Drivers { get; set; }
}
}
Here's a demo that gets the partial view dynamically from server.
Create a Handler OnGetDropdownListAsync(int tc) in your PageModel:
public class YourPageModel : PageModel
{
... other handler methods, e.g. OnGet() render the Index
public IActionResult OnGetDropdownListAsync(int tc)
{
var list = _context.Drivers.Select(a =>new SelectListItem{
Value = a.ID.ToString(),
Text = a.FullName,
}).ToList(); // or filter by Where( ... tc...).ToList()
return Partial( "/Pages/Shared/Selection.cshtml" , new DropdownListViewModel{
Drivers = list,
Index = tc,
});
}
}
Here the DropdownListViewModel is a plain ViewModel that holds the data:
public class DropdownListViewModel{
public IList<SelectListItem> Drivers{get;set;}
public int Index {get;set;}
}
Move your original html snippet within jQuery into a new partial view file: /Pages/Shared/Selection.cshtml
#using App.Pages
#model DropdownListViewModel
<div>
<select class="form-control dropdown" name="[#Model.Index].DriverID" asp-items="#Model.Drivers">
<option> Select a driver </option>
</select>
</div>
Finally, change your JavaScript to send an ajax request and update the UI in following way:
$("#AddButton").click(function () {
tc = tc + 1;
$("#totalContacts").val(tc)
$.ajax('?handler=DropdownList',{
method:"GET",
data:{ tc: tc },
success:function(d){ $(".addselection").append(d); }
});
});
[Edit]
You are passing currect ViewData to <partial> implicitly, which leads to this type error. You need change it to :
<partial name="/Pages/TestingPages/_SecondPage.cshtml" model="#Model.DropdownListViewModel" />
You're referencing an slim jQuery that doesn't have a ajax. Please change the script to <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>.
You're binding an event for #AddButton before this element has been created. You need wrap the js into a $(document).ready(function(){ .... }. You can also create a manually script after the #AddButton element. Or put the <script> into #section Scripts{} if you're using a default Layout which will make the script take effect after the page has been loaded.
Also you didn't initialize a tc variable.
In short, you need fix the bugs as below:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
var tc = 0;
$("#AddButton").click(function () {
tc = tc + 1;
$("#totalContacts").val(tc)
$.ajax('?handler=DropdownList', {
method: "GET",
data: { tc: tc },
success: function (d) { $(".addselection").append(d); }
});
});
});
</script>
...
<div class="addselection">
<partial name="/Pages/TestingPages/_SecondPage.cshtml" model="#Model.DropdownListViewModel" />
</div
I have a requirement which I need to display price based on drop down selection. and that price comes from same db, when I click one Test from dropdown then respected price of that test should display in textbox.The value is binding in textbox after selecting option from dropdown also it is displaying after taking span but not displaying on textbox, please tell me solution because i want to display it only on textbox .
here is Error Image
Model class
public partial class TwoDDiagnostic
{
public int TwoD_ID { get; set; }
public string TwoDDiagnostic_Name { get; set; }
public string TwoD_Price { get; set; }
public Nullable<System.DateTime> TwoD_Date { get; set; }
public Nullable<int> centr_Id { get; set; }
}
Controller
IEnumerable<SelectListItem> selectList2D = from twod in db.TwoDDiagnostics
where twod.centr_Id == Id
select new SelectListItem()
{
Text = twod.TwoDDiagnostic_Name,
Value = twod.TwoDDiagnostic_Name
};
var lasttwoD = db.TwoDDiagnostics.Where(x => x.centr_Id == Id).OrderByDescending(c => c.TwoD_ID).Take(1).FirstOrDefault();
if (lasttwoD == null)
{
ViewBag.twoDID = new SelectList(selectList2D, "Value", "Text");
model.ViewModel_TwoDDiagnostic = null;
return View(model);
}
string twodname = (from sub in db.TwoDDiagnostics where sub.TwoD_ID == lasttwoD.TwoD_ID select sub.TwoDDiagnostic_Name).First();
ViewBag.twoDID = new SelectList(selectList2D, "Value", "Text", twodname);
View
<div class="form-inline">
<label for="inputEmail1" class=" col-lg-2 col-sm-4 control-label">2D Diagnostic Services</label>
<div class="col-lg-5">
#Html.DropDownListFor(model => model.PTwoDDiagnostic_name, (SelectList)ViewBag.twoDID, "- Select 2D Diagnostics -", new { #class = "form-control ", #id = "twopID", #onchange = "fill()" })
</div>
<div class="col-lg-3">
#*<span class="form-control" id="twoprice"></span>*#
#Html.TextBoxFor(model => model.PTwoDDiagnostic_price, new { #class = "form-control ", #id = "twoprice" , #onchange = "fill()"})
</div>
</div>
here is json method
public JsonResult GetTwoDPrice()
{
AllViewModel model = new AllViewModel();
Session["Two_D"] = model.TwoD_ID;
var id = (int)Session["Two_D"];
if (!string.IsNullOrEmpty(Session["Two_D"].ToString()))
{
//int Id = (int)Session["Two_D"];
var Record = (from patient in db.TwoDDiagnostics
where patient.TwoD_ID == id
select new
{
TwoD_ID = patient.TwoD_ID,
TwoD_Price = patient.TwoD_Price
}).FirstOrDefault();
return Json(Record, JsonRequestBehavior.AllowGet);
}
return Json("", JsonRequestBehavior.AllowGet);
}
here is a script
<script type="text/javascript">
$("#twopID").on('change', function (event) {
$.ajax({
url: "#Url.Action("GetTwoDPrice", "Center")",
type: "Get",
success: function (data) {
debugger;
console.log(data.TwoD_Price);
$('#twoprice').text(data.TwoD_Price);
}
});
});
</script>
You need to use the jquery val() method to set the Value for the TextBox. If you use text() method, it sets the innerText of the input element (in between the <input> and </input> HTML tags) which is applicable only for HTML Elements like span, label, h, div, etc.
$('#twoprice').val(data.TwoD_Price);
Im developing a mvc5 application. In a view, using jquery i generate html elements(dropdownlists and textboxes) dynamically.
View briefly
#using (#Html.BeginForm("Save", "Item"))
{
#Html.DropDownListFor(a => a.MainGrpId, new SelectList(ViewBag.mnGrpList, "MainGroupId", "MainGroupName"), " Select a MainGroup", new { Class = "form- control", title = "", style = "width:175px;height:30px; margin-top:6px;" })
#Html.DropDownListFor(a => a.SubGrpId, new SelectList(ViewBag.sbGrpList, "SubGroupId", "SubGroupName"), " Select a SubGroup", new { Class = "form-control", title = "", style = "width:175px;height:30px; margin-top:6px;" })
<div id="ss" class="col-md-6">
</div>
#Html.TextBoxFor(a=>a.ItemName, new { Class = "form-control", placeholder = " Item Name", TextMode = "MultiLine2", onkeyup = "return validateChar(this)", style = "width:175px;height:25px;" })
<input type="submit" value="Save" class="btn btn-success" />
}
Jquery
var ss = $('#ss');
$('#SubGrpId').change(function () {
$('#ss').empty();
$.ajax({
url: '#Url.Action("FillItem", "Item")', // dont hard code your url's
type: "GET",
dataType: "JSON",
data: { MnId: $('#MainGrpId').val(), SbId: $(this).val() }, // pass the selected value
success: function (y) {
$.each(y, function (l, u) {
// add the label
var label = u.Name;
var name = 'Field' + l;
var label = $('<label></label>').text(label).attr('for', name);
ss.append(label);
if (u.Options.length==0) {
// There is only one item and its for generating a textbox
var input = $('<input>').attr({ type: 'text', id: name, name: name });
ss.append(input);
} else {
// Its a select
var select = $('<select></select>').attr({ id: name, name: name });
// add each option
$.each(u.Options, function (i, option) {
select.append($('<option></option>').val(option.Value).text(option.Text));
})
ss.append(select);
}
});
},
error: function () {
alert("something wrong");
}
});
});
ItemViewModel
public class ItemViewModel
{
public string ItemName { get; set; }
public int MainGrpId { get; set; }
public int SubGrpId { get; set; }
public string Field0 { get; set; }
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public string Field4 { get; set; }
public string Field5 { get; set; }
}
Altogether number of dynamically generated ddls+textboxes are equal or less than 6. What i want to do is when user selects an item from a ddl or enters a value to a texbox, the value in that particular element(string) should be shown in 'ItemName' textbox. User can go on adding like that. Each added value(string) should be shown separated by a space in 'ItemName' textbox.
Futher every ddl and textbox(only dynamically generated ones-Field0, Field1, Field2, Field3, Field4, Field5, ) should get enabled one by one(one after another) allowing user to select(ddls)/enter(textboxes). But im struggling to develop the correct jquery function for this whole scenario. Pls help me with this. Thanks!
Controller:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class ExperimentalController : Controller
{
public ActionResult ReloadTest1()
{
string temp = DateTime.Now.ToString();
ViewBag.Time = temp;
return View();
}
public PartialViewResult ReloadTest1Partial()
{
string temp = DateTime.Now.ToString();
ViewBag.Time = temp;
return PartialView();
}
}
View:
#{
ViewBag.Title = "ReloadTest1";
string time = this.ViewBag.Time;
ViewData["date"] = time;
ViewBag.TheTitle = "test";
}
<h2>ReloadTest1</h2>
<select id="iSelect" name="iSelect" >
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<div id="myPartialViewContainer">
#{Html.RenderPartial("_ReloadTest1Partial", null, new ViewDataDictionary { {"vb", ViewBag}});}
</div>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$('#iSelect').on('change', function () {
$("#myPartialViewContainer").load('#(Url.Action("ReloadTest1Partial", "Experimental", null, Request.Url.Scheme))')
})
</script>
Partial View:
#{
var vb = ((dynamic)ViewData["vb"]);
}
<div>
<span>#vb.Time</span>
</div>
What is not working:
Passing the viewbag/viewdata directly from controller to partial view because mvc does not accept that to happen.
What is working:
from the above code you can see that the partial view gets the data ONCE with the Html.RenderPartial method and the viewbag passing down.
the reload does work on change of the selected object in the dropdown
What is needed:
I need to pass data to the partial view when it is reloaded or afterwards, this is mainly a test setup but i finally want to be able to update tables dependant on the select value.
If somone is able to give me a working example please do so.
In your controller you;re using ViewBag to set custom value, but in your view you are working with ViewData as well as referring to a different name (you're setting ViewBag's Time property in controller, but you expect ViewData's vb property in the view).
Change your view to expect model`:
#model MyModel
#{
string time = "";
if (ViewData["Time"] != null)
{
time = ViewData["Time"];
}
}
<div>
<span>#Model.Time</span>
</div>
And change you controller to pass it:
public ActionResult ReloadTest1()
{
var model = new MyModel {Time = DateTime.Now.ToString()};
return View(model);
}
public PartialViewResult ReloadTest1Partial()
{
var model = new MyModel {Time = DateTime.Now.ToString()};
return PartialView(model);
}
And you master view file will look like this:
#model MyModel
<div id="myPartialViewContainer">
#{Html.RenderPartial("_ReloadTest1Partial", model);}
</div>
And create your model:
public class MyModel
{
public string Time {get;set;}
}
As a side not, it's always preferable to use a strongly-typed model instead of ViewBag or ViewData as you can get compilation errors and IntelliSense
Final solution:
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace RolloutTool.Controllers
{
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class ExperimentalController : Controller
{
public ActionResult ReloadTest1()
{
var model = new RolloutTool.Models.ExperimentalViewModels.MyModel { Time = DateTime.Now.ToString() };
string temp = DateTime.Now.ToString();
ViewBag.Time = temp;
ViewData["Time"] = temp;
return View(model);
}
[HttpPost]
public PartialViewResult ReloadTest1Partial(string test)
{
var model = new RolloutTool.Models.ExperimentalViewModels.MyModel { Time = DateTime.Now.ToString() };
string temp = DateTime.Now.ToString();
ViewBag.Time = temp;
ViewData["Time"] = temp;
return PartialView("_ReloadTest1Partial", model);
}
// GET: Experimental
public ActionResult Experimental()
{
ViewBag.Message = "Your contact page.";
ViewBag.TestValue = 10;
string[] temp = { "alpha", "beta", "gamma", "delta" };
ViewBag.names = temp;
int temp2 = temp.Length;
ViewBag.nameslength = temp2;
return View();
}
}
}
View:
#{
ViewBag.Title = "ReloadTest1";
string time = this.ViewBag.Time;
ViewData["date"] = time;
ViewBag.TheTitle = "test";
}
#model RolloutTool.Models.ExperimentalViewModels.MyModel
<h2>ReloadTest1</h2>
<select class="chosen-select" id="iSelect" name="iSelect">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<div id="myPartialViewContainer">
#{Html.RenderPartial("_ReloadTest1Partial", Model);}
</div>
#Styles.Render(
"~/content/chosen/chosen.css",
"~/content/chosen/prism.css",
"~/content/chosen/style.css",
"~/content/bootstrap.css",
"~/content/Site.css")
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen/chosen.jquery.js"></script>
<script src="~/Scripts/chosen/prism.js"></script>
<script>
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
</script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$('#iSelect').on('change', function () {
getPartial();
})
</script>
<script>
function getPartial() {
var tempSelect = document.getElementById("iSelect");
var tempResult = tempSelect.options[tempSelect.selectedIndex].text;
$.ajax({
url: "ReloadTest1Partial",
type: "POST",
data: {'test' = tempResult}, //if you need to post Model data, use this
success: function (result) {
$("#myPartialViewContainer").html(result).find("select").each(function () {
$(this).chosen({});
}
});
}
</script>
#{
string time = "";
string temp = "";
if (ViewData["vb"] != null)
{
temp = "1";
time = ((dynamic)ViewData["vb"]).Time;
}
else if (ViewContext.Controller.ViewBag.Time != null)
{
temp = "2";
time = ViewBag.Time;
}
else if (ViewData["Time"] != null)
{
temp = "3";
time = (string) ViewData["Time"];
}
}
#model RolloutTool.Models.ExperimentalViewModels.MyModel
<div>
<span>#time</span>
<span>#Model.Time</span>
<span>#temp</span>
</div>
<select class="chosen-select"></select>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen/chosen.jquery.js"></script>
<script src="~/Scripts/chosen/prism.js"></script>
This updates the partial view correctly AND reloads the chosen-select dropdowns. (see styles and scripts not working in partial view)
I have looked at other SO topics on this and they end up being either really old or using WebForms. I have an MVC view in which I have two listboxes. I want to move items back and forth between the two listboxes. The View 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" />
#Html.ListBoxFor(m => m.SelectedAttributes2, Model.SelectedItems, new { id = "listBoxSel", SIZE = 5})
}
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 code 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 used JQuery to try to do this but it's not working (nothing gets transferred to 2nd listbox). Anyone kinow what's wrong?
<script src="~/Scripts/jquery-2.1.1.js"></script>
<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>
Replace buttons type from submit to to button like below
<input type="button" name="add" id="add" value="MoveRight" />
<input type="button" name="remove" id="remove" value="MoveLeft" />
In your JavaScript correct selectors prepend # to ids, it should work!
$("add") to $("#add")
and
$("remove") to $("#remove")
If you want you can reduce it to
<script>
$(function() {
$(document)
.on("click", "#add", function() {
$("#listBoxAvail :selected").remove().appendTo("#listBoxSel");
})
.on("click","#remove", function() {
$("#listBoxSel :selected").remove().appendTo("#listBoxAvail");
});
});
</script>
You can use the jQuery-Dual-Listbox plugin for jQuery. It requires a bit of setup but then works well enough in the MVC environment. One caveat is that in order for your selected values in the 2nd listbox to be posted back to the server for processing, you need to ensure that all items in that listbox are selected before the form gets submitted.
e.g. for your markup:
<script src="jQuery.dualListBox-1.3.js" type="text/javascript"/>
<script type="text/javascript">
$(function () {
$.configureBoxes({
box1View: 'listBoxAvail',
box2View: 'listBoxSel',
to1: 'remove',
to2: 'add',
allTo1: 'remove-all', //you must create this button
allTo2: 'add-all', //you must create this button
useFilters: false
});
});
$("#listBoxSel").closest("form").on("submit",
function() {
//only selected options in listbox get POSTed back!
$("#listBoxSel > option").prop("selected", true);
return true;
}
}
</script>
Source