Send Chosen Selected Values Array to Controller - MVC - javascript

So, I have a view with a chosen search box, a button "Add" (btn-default) and a button "Edit" (breadcrumb) . When I click the Add button, the ajax sent me a table with the values (in this case, funcionaries) selected in the chosen text box.
I want that, when I click on the Edit button, send the chosen values (can be one, or hundreds of values) to another controller to return another view.
Don't want to use ajax because I want to use a new view on totally.
On the controller side, when I send the data with javascript, I always get null. Why?
View
<script>
$(document).ready(function () {
$(".btn-default").on("click", function (event, params) {
$.ajax({
url: '#Url.Action("EditarPonderacoesEspecial", "Sorteios")',
type: 'POST',
dataType: 'html',
cache: false,
traditional: true,
data: { bdoIds: $(".chosen-select").val() },
success: function (responseText, textStatus, XMLHttpRequest) {
$("#MyDiv").empty();
$("#MyDiv").html(responseText);
},
error: function () { }
})
});
$(".breadcrumb").on("click",function (event, params) {
bdoIds = $(".chosen-select").val();
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", bdoIds);
});
});
Controller
public ActionResult EditarPonderacoesEspecialSecond(string[] bdoIds)
{
//do whatever I want with the bdoIds
return View();
}
I had tried many different ways, but the controller always receive the parameter as null. What I am doing wrong? Thanks!

Your controller action is expecting an array of strings.
Assuming .chosen-select is a select list as that part is missing from the question.
First read the selected values into an object as follows:
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
Then send them as follows:
$(".breadcrumb").on("click",function (event, params) {
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", { bdoIds: selectedValues });
});

Declare Global array like
var SelectedArray = new Array();
When you select multiple selectlist item each time push value in SelectedArray
$('#ChosenId').chosen().change(function () {
SelectedArray = $('#ChosenId').chosen().val();
});
Then your ajax data is like
data: { bdoIds: SelectedArray },

Related

Adding to JSON array by HTML button

I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.

Updating a div based on a select event from KendoUI Widget

I have a KendoUI search bar that has a drop down of autocompleted items based on what I type. When I type into I get a drop down menu. When I click on an item in the drop downlist, I want two things to happen. One which works, and that is loading a partial view. But, the other thing deals with updating a div element that is also in that partial view.
The partial view
#{
ViewBag.Title = "Client";
}
<div id="update">#ViewBag.name</div>
<p id="ahhh"></p>
External Javascript function
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
alert("IT WORKED");
},
error: function (result) {
alert("FAILED");
}
})
}
In the HomeController there is a method called someStuf. I am sending that item that is clicked on the event into the someStuf method.
Now here are the two controller methods that I'm working with.
Secretary s = new Secretary();
public ActionResult Client()
{
ViewBag.name = s.Client;
return PartialView();
}
[HttpPost]
public JsonResult someStuf(String n)
{
s.Client = n;
return Json(n, JsonRequestBehavior.AllowGet);
}
So then I update a class with that value that was passed from javascript. I then add that new value to the viewbag for the partial view Client.
Sorry for the misleading variables. Client is a type of model. Then I always have a partial view that is called client.
When I try this. The ViewBag is not showing the result that I would like. I can get the client side to send to the server. But I can't get the server to send to the client.... I bet it's something simple. But I'm trying to understand this step so I can use the same method to update id and class elements.
<p class="CompanySearchBar">
#(Html.Kendo().AutoComplete()
.Name("companyComplete") //The name of the AutoComplete is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("company") //Specify which property of the Product to be used by the AutoComplete.
.BindTo(Model)
.Filter("contains")
.Placeholder("Company name")
.Events(e => { e.Select("onSelect"); })
)
</p>
The above code allows for a search bar with autocomplete. While typing for an item a drop down list shows up with results having the same substring. When clicking one of the results the onSelect method is activated.
you can give like this and on change event just assign a value using jquery like
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
$('#ahhh').text(result.NAME); //the object which you returns from the controller
},
error: function (result) {
alert("FAILED");
}
})
}
<label id=ahhh></label>

Url action parameters using Ajax

I am trying to pass data from a view to a controller using parameters.
Now I am running a few difficulities. I am trying to pass those parameters once I select a row from a table and press on a button which has a onclick method to ShowTasks()
The C# controller:
[Route("/service/delivery/{id}/{shopdoccode}/{regdate}")]
public ActionResult Delivery(string id, string shopdoccode, string regdate)
{
//do stuf
}
The Javascript function when user clicks on button:
function ShowTasks() {
//Dear Stackoverflow > This works, this is for selecting a row in the table
var $selectedRow = $(".highlight");
if ($selectedRow.length == 1) {
var dcColumn = 0;
var rdColumn = 1;
var shopdoccodeColumn = 3;
//assigning name to the colomn value
var id = $selectedRow[0].children[dcColumn].innerText.trim();
var regdate = $selectedRow[0].children[rdColumn].innerText.trim();
var shopdoccode = $selectedRow[0].children[shopdoccodeColumn].innerText.trim();
//ajax
if (id && regdate && shopdoccode) {
$.ajax({
type: 'POST',
url: '#Url.Action("service", "delivery" ,new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
data: { id, regdate, shopdoccode },
success: function (data) {
if (data.success) {
console.log("Succes");
}
},
error: function (data) {
console.log("Error");
}
});
}
}
}
What have I done so far? Sitting for hours trying to find a way to give the parameters to my controller so I can invoke a SQL stored procedure.
Unforntunately I can not simply use a hidden form for this.
Also this was quite helpful:
Url.Action parameters?
#sleeyuen
Looks to me like your Url.Action has its parameters in the wrong order. Change it to:
url: '#Url.Action("delivery", "service", new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
Here's the appropriate overload that you want:
Action(String, String, Object) with actionName, controllerName, and routeValues, in that order.
You can not *.js or *.html file wrtie razor code.
#Url.Action(string actionName,string controllerName,object routeValues)
The above code can only be used *.cshtml file.
test with Url.RouteUrl instead of Url.Action

pass List from Jquery to view

I want to pass list from jquery ajax to the particular view. In a view user select the type. If they select first type, then it will load two lists and pass to the particular view data. How to do this in Ajax Jquery?
<%:Html.RadioButtonFor(model=> model.Type, 1)%> Type 1
<%:Html.RadioButtonFor(model=> model.Type, 2)%> Type 2
$("#Type").change(function () {
var type = $("#Type");
if (type == 1) {
//*****The following things are added from controller. i want to pass the following lists from ajax*******/
List<SelectListItem> type= new List<SelectListItem>();
type.Add(new SelectListItem { Text = "one", Value = "14" });
type.Add(new SelectListItem { Text = "two", Value = "12" });
}
});
how to do this
I'm presuming that you want to submit the form to pass the value to the view?
If so, in the view with the form elements have the AJAX call:
<script>
$(document).ready(function() {
$("#the-form-id").on("submit", function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/your-controller-name/your-action-name,
data: $("#the-form-id").serialize(),
success: function(data) {
//do something with the View that is returned...
}
});
});
});
</script>
Then, you;'ll need an action in the controller the AJAX is calling that accepts the "data" being passed from the form. In ASP MVC, this will normally be a corresponding Model.
Said action will return a View set up however you want it to be. The original AJAX call will receive this so you can utilize it however you want to.
Hope that helps.

Add array of items into kendo ui multi select

please pardon my noobness, but I'm new to working with Telerik controls. I have seen many examples of this but they haven't been able to solve my problem. I have a Kendo UI multiselect widget which contains some items and a button which, on clicking, would fill the multiselect widget partially with some items. These items are obtained as JSON from a controller method (ASP.NET MVC). So, the button click actually fires an ajax request and on successfully firing up, it calls a javascript function to fill the multiselect widget up. As of now, the ajax gets fired successfully and the data that I want is coming back successfully, just that the multiselect is not displaying the values.
My javascript/AJAX methods:
function addItems(items) {
var values = new Array();
for (var i = 0; i < items.length; i++) {
values[i] = items[i].Item.ID;
// gets values back correctly
console.log(values[i]);
}
// print values
$('#items').data("kendoMultiSelect").value(['"' + values + '"']);
};
// success
$(document).on("click", "#add-items-button", function () {
var myUrl = $('#MyURL').val();
$.ajax({
url: myUrl, // get URL from view
method: 'GET',
dataType: 'json',
success: function (data) {
addItems(data);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
My multiselect widget is a partial view so:
#using Kendo.Mvc.UI
#(Html.Kendo().MultiSelect()
.Name("items") // Name of the widget should be the same as the name of the property
.DataValueField("ID")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["items"])
.Placeholder("Add Items")
)
Am I missing something very obvious? Am I writing the data back in an incorrect format to the multiselect widget? Please help.
You need to add items to the data source of the multiselect.
$('#items').data("kendoMultiSelect").dataSource.add( { ID: 1, Name: "Name" });
Here is a live demo: http://jsbin.com/eseYidIt/1/edit
It might help to others
var multiSelect = $('#mymultiSelect').data('kendoMultiSelect');
var val = multiSelect.value().slice();
$.merge(val, "anil.singh#hotmail.com");
multiSelect.value(val);
multiSelect.refresh();
OR
$('#mymultiSelect').data("kendoMultiSelect").dataSource.add({Id:"EMP100XYZ",
EmailId: "ayz#gmail.com" });

Categories