Updating a div based on a select event from KendoUI Widget - javascript

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>

Related

Null value is always sending from AJAX to controller class whenever a value is selected from drop down

I want to fetch data from the database whenever the user selects a value from drop down. For these purpose I have written a block for code, in which a JavaScript function is call whenever a user selects a value from drop down and passes that value to the controller through ajax. Below is the snapshot of the code.
cshtml
#Html.DropDownList("Code", null, htmlAttributes: new { #class = "form-control", #onchange = "fetchData(this.value)" })
JS
<script>
function fetchData(Code) {
$.ajax({
url: '#(Url.Action("fetchCode", "ChargesSetup"))',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'Code':'" + Code + "'}",
contentType: false,
processData: false,
success: function (result) {
console.log(result);
},
error: function (result) {
console.log("E");
}
});
}
</script>
NOTE: I have tried my format for passing data to controller, the value
of code inside JavaScript is correct as 'A'. But in controller class
is show as #p__linq__0. when I hard code the value of code the controller
work fine.
Controller
[HttpPost]
public JsonResult fetchData(string Code)
{
IQueryable chargestable = from p in db.chargestable where (p.Code == Code) select p;
return Json(chargestable , JsonRequestBehavior.AllowGet);
}
In JavaScript the value of drop down is exactly same what we want:
but after AJAX call, in controller the value of drop down is change to some thing like #p__linq__0
{SELECT
[Extent1].[area] AS [area]
FROM [dbo].[chargestable] AS [Extent1]
WHERE [Extent1].[Code] = #p__linq__0}
What is problem with my code? How can I resolve this as I need to get the buffer of chargestable whenever drop down value is selected.
By changing return statement makes no effect because the value of parameter is not set, its always null.
return Json(chargestable.ToList(), JsonRequestBehavior.AllowGet);

Send Chosen Selected Values Array to Controller - MVC

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 },

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" });

Execute a controller action from jQuery/javascript

I have a ListBox in my view - when I select an item from the list box, I want to call a controller method, execute a lookup on that value, then redraw the page with those values.
My listbox code and my jQuery code looks like this:
#using (Html.BeginForm())
{
...
<h3>Environments</h3>
#Html.ListBox("Environment",
new SelectList(Model.Environments),
new {#id="environmentsListbox"})
...
}
<script>
$(document).ready(function () {
$('#environmentsListbox').click(function () {
var selected = $('#environmentsListbox').find(":selected").text();
$.ajax({
url: '#Url.Action("Index")',
data: { selectedEnvironment: selected },
success: function(data) {
---- What to do here?
}
});
});
});
</script>
The controller method looks like this:
public ActionResult Index(string selectedEnvironment)
{
// code omitted for brevity...
var frameworkConfig = GetInfo(selectedEnvironment);
return View(frameworkConfig);
}
The call works correctly, the selected text does make it to the controller method....however what do I do with the result? I'm looking for something comparable to #Html.Action("Index", selectedEnvironment) that you would use in a normal MVC context (non-js). I have the returned View code in the data variable, is there a way to reload the page with that value?
I've seen the answer in this post: How to call URL action in MVC with javascript function? and is very close to what I need to do, however the resulting view code from that controller method is pushed into a contained div tag, not the current view.
You can use jQuery's .html() function. Inside your success callback, do something like this:
<script>
$(document).ready(function () {
$('#environmentsListbox').click(function () {
var selected = $('#environmentsListbox').find(":selected").text();
$.ajax({
url: '#Url.Action("Index")',
data: { selectedEnvironment: selected },
success: function(data) {
$('#container').html(data);
}
});
});
});
</script>
You want to make sure that the view you are returning from your controller has the markup that you need (without any layout code etc). Access that url directly in the browser to see what it returns.

Categories