Save multiple selected data - html

With this code on my form I want to save the selected Cars (all its data - id and description):
<div class="editor-field">
#Html.DropDownListFor(model => model.Cars, new SelectList(Model.ListCars, "Description", "Description"), new { id = "myCars", multiple="multiple" })
#Html.ValidationMessageFor(model => model.Cars)
</div>
but when I check if Model.IsValid, it's set to false and in my view I got this message: The value '(selected)' is invalid.
Can anyone tell me why and how can I solve this?
My viewModel:
public ICollection<Car> Cars;
public ICollection<Car> ListCars; //it's populated somewhere
My Car.cs:
public int Id { get; set; }
public string Description { get; set; }

I developed a solution that doesn't consider a good practice, but at least it solved my problem. Basically my logic is as follows:
Use a plugin for the dropdown helper
Have somewhere a hidden div with all the selectable values ​​passed to the dropdown helper (id and description)
When there is a change in the selected dropdown through JS item, "select" in the hidden div desired values ​​by assigning them a specific name in order to be saved
Like this:
1. Use a plugin for the dropdown helper:
I used this JS plugin (v0.6) on my dropdowns, so I have this changes:
My dropdown helper:
#Html.DropDownListFor(model => model.Cars, new SelectList(Model.ListCars, "Description", "Description"), new { id = "myCars", #class = "isCheckList", multiple="multiple" })
In my JS:
$(document).ready(function () {
$(".isCheckList").dropdownchecklist({ firstItemChecksAll: true, width: 350 });
});
2. Have somewhere a hidden div with all the selectable values ​​passed to the dropdown helper (id and description):
<div id="carsHidden" style="display:none">
#foreach (Caritem in Model.ListCars)
{
<div id="#(item.Id)">
#Html.HiddenFor(modelItem => item.Id, new { data_Name = "Id" })
#Html.HiddenFor(modelItem => item.Description, new { data_Name = "Description" })
</div>
}
</div>
3. When there is a change in the selected dropdown through JS item, "select" in the hidden div desired values ​​by assigning them a specific name in order to be saved:
For this, I add an event onchange to my dropdown helper and manager that selection:
$(".isCheckList").on("change", function (e, data) {
var hiddenDivId = $(this).data("hiddendivid");
var fieldName = $(this).data("fieldname");
selectManagement($(this), data, hiddenDivId, fieldName);
});
function selectManagement(e, data, hiddenDivId, fieldName) {
$(e).children().each(function () {
if ($(this).attr("value") == $(data).attr("value")) {
if ($(this).attr("selected")) {
$("#" + hiddenDivId + " #" + $(this).attr("value")).addClass("IsSelected");
selectComponent(hiddenDivId, fieldName);
}
else {
$("#" + hiddenDivId + " #" + $(this).attr("value")).removeClass("IsSelected");
unselectComponent(hiddenDivId);
updateRowsIds(hiddenDivId, fieldName);
}
return false;
}
});
}
function unselectComponent(hiddenDivId) {
$("fieldset").each(function () {
if ($(this).find("div#" + hiddenDivId).exists()) {
$("div#" + hiddenDivId).children().each(function () {
if ($(this).hasClass("IsSelected") == false) {
$(this).find("input").each(function () {
$(this).attr("name", null);
$(this).attr("id", null);
});
}
});
}
});
}
function selectComponent(hiddenDivId, fieldName) {
$("fieldset").each(function () {
if ($(this).find("#" + hiddenDivId + " .IsSelected").exists()) {
var index = 0;
$("#" + hiddenDivId + " .IsSelected").each(function () {
$(this).children().each(function () {
if ($(this).is("input")) {
$(this).attr("name", fieldName + "[" + index + "]." + $(this).data("name"));
$(this).attr("id", fieldName + "_" + index + "_" + $(this).data("id"));
}
});
index++;
});
}
});
}
function updateRowsIds(hiddenDivId, fieldName) {
$("#" + hiddenDivId + " div.IsSelected").each(function (index) {
$(this).find("input").each(function () {
$(this).attr("name", fieldName + "[" + index + "]." + $(this).data("name"));
});
});
}
So now, always I select a Car I will save its Description and ID

Related

Angular 6 . I Want to change the interval dynamically according to the value given in the array

This is my set-interval and I want to change the interval dynamically according to the value given in the array.
setInterval(() => {
this.getwebsiteurl();
this.count++;
if (this.count > this.data1.length) {
this.count = 0;
}
}, this.filtered[this.count].timeout);
getwebsiteurl() {
if (this.count < this.data1.length) {
this.http
.get("assets/" + this.len + "/" + this.data1[this.count].HtmlName + ".html", {
responseType: "text"
})
.subscribe((data: any) => {
this.htmlfile = data;
});
}
}
Filtered Array contains

Values not displaying in Listbox from database using mvc5

in controller json method getting columnnames (Account,EmailTo,Subject,MessageContent) like this in ReportColumnsList ..but i need to pass these values in view page and display in listbox..
data is getting as [Object Object] and also displaying in listbox like this..
please give me solution regarding this..
Thanks & Regards
in Controller part :-
[AllowAnonymous]
public ActionResult GetColumnsByFavouriteReport(ReportsModel Model,string Columns)
{
List<Report> ReportColumnsList = MCPAdminControllerPageObject.GetColumnsByReportName(Columns);
return Json(ReportColumnsList, JsonRequestBehavior.AllowGet);
}
In view Part:-
$(document).ready(function () {
$('#FavouriteReports').change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetColumnsByFavouriteReport", "MCPAdmin")',
data: { Columns: $('#FavouriteReports').val() },
datatype: "json",
traditional: true,
success: function (data) {
$('#SelectedFields').empty();
$.each(data, function (key, val) {
$('#SelectedFields').append('<option id="' + key + '">' + val + '</option>');
})
}
});
});
#Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { #class = "form-control editable" })
Let me assume Your model class Report
public class Report {
public int ReportId { get; set; }
public Name ReportName { get; set; }
}
Inside your ajax method
if(data!=null) {
$('#SelectedFields').empty();
var dd = null ;
$.each(data, function (key, val) {
dd += "<option " + " value=" + val.ReportId + ">" + val.ReportName + "</option>";
});
//append to given id
$('#SelectedFields').append(dd);
}
I hope this will help your, bind your dropdown list

Autcomplete using Jquery Ajax in JSP

I am trying to follow this example
and I have the following in JSP page
(getData.jsp)
Department t = new Department ();
String query = request.getParameter("q");
List<String> tenders = t.getDepartments(query);
Iterator<String> iterator = tenders.iterator();
while(iterator.hasNext()) {
String deptName= (String)iterator.next();
String depto = (String)iterator.next();
out.println(deptName);
}
How can I use the above to use in Jquery autcomplete? When I tried there was no output coming.
My Jquery autoComplete code
<script>
$(function() {
$( "#dept" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getData.jsp",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.<??>, function( item ) {
return {
label: item.name + (item.<??> ? ", " + item.<??> : "") + ", " + item.<??>,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
alert(ui.item.label);
}
});
});
</script>
Is your response in JSON format?
Here's what I do when I use Jquery UI Autocomplete:
Create a class whose parameters are the ones you will use when you say item.name
public string Pam1{ get; set; }
public string Pam2{ get; set; }
public string Pam3{ get; set; }
public SomeResponse(string SomePam)
{
// Pam1 = ???
// Pam2 = ???
// Pam3 = ???
}
In your handler:
context.Response.ContentType = "application/json";
string query = (string)context.Request.QueryString["query"];
var json = new JavaScriptSerializer();
context.Response.Write(
json.Serialize(new SomeResponse(query))
);
context.Response.Flush();
context.Response.End();
EDIT
The javascript (Here is an example where the user can choose more than one option, separated by coma. If you don't want that, remove it.) txt_autocomplete is the class of the TextBox.
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".txt_autocomplete")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function (request, response) {
$.getJSON("handlers/autocomplete.ashx?query=" + extractLast(request.term), {
term: extractLast(request.term)
}, response);
},
search: function () {
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.Pam1);
terms.push("");
this.value = terms.join(", ");
console.log("Pam1 is :" + ui.item.Pam1 + " Pam2 is: " + ui.item.Pam2 + " Pam 3 is : " + ui.item.Pam3);
return false;
}
});
});

How to rebind Json object with Telerik MVC grid

Im having problem with rebinding grid with Json object….
Im trying to create custom delete button…
So far I have Jquery function: Gets an ID of selected column (username) and call controller action “UserDetails”
Delete button:
$("#DeleteUser").click(function () {
if (id != "") {
var answer = confirm("Delete user " + id)
if (answer) {
$.ajax({
type: "POST",
url: "/Admin/UserDetails",
data: "deleteName=" + id,
success: function (data) {
}
});
}
} else {
$("#erorMessage").html("First you must select user you whant to delete!");
}
});
This is action controller UserDetails(string startsWith, string deleteName)
[GridAction]
public ActionResult UserDetails(string startsWith, string deleteName)
{ // Custom search...
if (!string.IsNullOrEmpty(startsWith))
{
return GetSearchUserResult(startsWith);
}
if (!string.IsNullOrEmpty(deleteName))
{
TblUserDetails user = db.TblUserDetails.Single(a => a.TblUser.userName == deleteName);
try
{
TblUser userToDelete = db.TblUser.Single(a => a.userId == user.TblUser.userId);
db.DeleteObject(user);
db.DeleteObject(userToDelete);
db.SaveChanges();
Membership.DeleteUser(deleteName);
List<UserDto> retModelData = new List<UserDto>();
//GetAllUsers() returns a List<UserDto> of users.
retModelData = GetAllUsers();
var model = new GridModel
{
Data = retModelData,
Total = GetAllUsers().Count()
};
return View(model);
}
catch
{
return View(new GridModel());
}
}
else
{
var user = GetAllUsers();
return View(new GridModel(user));
}
}
So far everything is working OK. But can I bind my grid with these Json data and how???
This is my Json result that I want to bind with grid...
And here is my grid:
#(Html.Telerik().Grid<App.Web.Models.UserDto>()
.Name("Grid")
.DataKeys(key =>
{
key.Add(a => a.Id);
})
.Columns(column =>
{
column.Bound(a => a.Username).Filterable(false);
column.Bound(a => a.FirstName).Filterable(false);
column.Bound(a => a.LastName).Filterable(false);
column.Bound(a => a.Email).Filterable(false);
})
.DetailView(detailView => detailView.ClientTemplate(
"<table id='DetailTable'><tbody><tr class='UserRow'><td class='Tbllable'><b>First name</b></td><td><#= FirstName #></td>"
+ "<td></td><td></td>"
+ "</tr><tr><td class='Tbllable'><b>Last name</b></td>"
+ "<td><#= LastName #></td>"
+ "<td id='Roles'></td><td id='Operations'></td>"
+ "</tr><tr><td class='Tbllable'><b>Username</b></td><td><#= Username #></td></tr><tr><td class='Tbllable'><b>Address</b></td>"
+ "<td><#= Address #></td></tr><tr><td class='Tbllable'><b>Email</b></td><td><#= Email #></td></tr><tr><td class='Tbllable'><b>Birth date</b></td>"
+ "<td></td></tr><tr><td class='Tbllable'><b>Registration date</b></td><td></td></tr><tr><td class='Tbllable'><b>Phone number</b></td>"
+ "<td><#= PhoneNumberHome #></td></tr><tr><td class='Tbllable'><b>Mobile number</b></td><td><#= PhoneNumberMobile #></td></tr></tbody></table>"
))
//.EnableCustomBinding(true)
.DataBinding(bind => bind.Ajax().Select("UserDetails", "Admin", new { startsWith = ViewBag.startsWith }))
.Pageable(paging =>
paging.PageSize(12)
.Style(GridPagerStyles.NextPreviousAndInput)
.Position(GridPagerPosition.Bottom)
)
.ClientEvents(e => e
.OnRowDataBound("Expand")
.OnRowSelect("select")
.OnLoad("replaceConfirmation")
)
.RowAction(row =>
{
if (row.Index == 0)
{
row.DetailRow.Expanded = true;
}
})
.Editable(editing => editing.Mode(GridEditMode.PopUp))
.Selectable()
.Sortable()
)

How to populate a #html.dropdownlist mvc helper using JSon

I have a <select> which is loaded by a JSon. But I want to use "#html.dropdownlist helper" instead. My Json is:
function LoadSites() {
$("SelectSite").html("");
$.getJSON("/Pedido/GetSite", null, function (data) {
$("#SelectSite").append("<option value=0>Selecione...</option>");
$.each(data.Result, function (index, site) {
$("#SelectSite").append("<option value='" + site.Id + "'>" + site.Nome + "</option>");
});
});
this Json populate this...
<select id="SelectSite"></select>
My Controller:
[HttpGet]
public JsonResult GetSite()
{
Repository<Site> siteRepo = new Repository<Site>( unitOfWork.Session );
return this.Json( new { Result = siteRepo.All() }, JsonRequestBehavior.AllowGet );
}
I want my code more reusable and self-documenting.
How can I send the object "site" from JSon to "cshtml" using dropdownlist to do something like #html.dropdownlist(site.id, site.Nome)???
Is there a way?
Tks guys.
In your view:
#Html.DropDownListFor(x => x.SiteId, new SelectList(Enumerable.Empty<SelectListItem>()))
where SiteId is a property of your view model which will receive the selected site id when the form is submitted.
and then you could populate this dropdown using AJAX:
$(function() {
$.getJSON('#Url.Action("GetSite", "Pedido")', function(result) {
var ddl = $('#SiteId');
ddl.empty();
$(result).each(function() {
ddl.append(
$('<option/>', {
value: this.Id
}).html(this.Nome)
);
});
});
});
and the controller action that would return the JSON data:
public ActionResult GetSite()
{
var sites = new[]
{
new { Id = "1", Nome = "site 1" },
new { Id = "2", Nome = "site 3" },
new { Id = "3", Nome = "site 3" },
};
return Json(sites, JsonRequestBehavior.AllowGet);
}