pass List from Jquery to view - javascript

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.

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>

How to use Partials in ASP MVC when used with Javascript to call a Controller Action?

new kid on the block w/ASP MVC ... tryna get an Edit form going in a JavaScript dialog box.
my current plan of action:
Main view has the edit button which onClick grabs the record_id, and makes an ajax call to my Controller-Action passing the record_id as the param.
In the same view, I am using a partial "_EditApp" which has the tabs/dialog related code.
In the same onClick, I am loading up the tabs that I specify in _EditApp.
JS ..
$('.btn_edit_app').click(function () {
var app_to_edit = $(this).attr('id');
$.ajax({
url: '/Application/editApp',
contentType: 'application/html; charset=utf-8',
data: { app_id: app_to_edit},
type: 'GET',
dataType: 'html',
success: function (result) {},
});
$('#edit_tabs').tabs({ active: 0 });
$('#edit_dialog').dialog({ width: 700, height: 400 });
});
my Controller/Action
public ActionResult editApp(int app_id)
{
AppDBServer ads = new AppDBServer();
ads = findADS(app_id);
return View("_EditApplication", ads);
}
the problem ...
simply, I want to retrieve the record and populate the tabs and dialog box with the retrieved data fields. Hence passing the model to the EditApplication Partial.
The issue is I am using the same partial in my main view that I am in the controller action and not sure how to go about this ... Ideas, or even a newer approach to this would be A-OK.
Also, I aiming to have data retrieval handled by the Controller / Action.
Thank you, SOF fam!
I only wanted to comment but I can't since I have less than 50 reputation. Anyways, if I understand correctly you want to pull up some tabs after a an action call. I've had to something like this before. Here was my solution:
onclick of the button or row with the ID call an ActionResult.
Or use an Ajax Form:
#using (Ajax.BeginForm("GetTabs", "ControllerHere", new AjaxOptions() { LoadingElementId = "loading", UpdateTargetId = "targetdiv", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }))
{
#Html.Hidden("id", id)
....
Submit
}
Return a PartialView i.e. "_Tabs" and pass the model (id in this case).
`
public ActionResult GetTabs(string id)
{
....
//pass id or get model and pass model
return PartialView("_Tabs", id);
}
`
Within the _Tabs.cshtml call Html.RenderAction for each tab.
(I had set up tabs using bootstrap)
Html.RenderAction takes an action method name and you can pass parameters.
`#{Html.RenderAction("GetTab1",new {id = #id}) }
#{Html.RenderAction("GetTab2",new {id = #id}) }`
..etc
Each Action will return a partial view...
public ActionResult GetTab1(string id)
{
//get data
model = id lookup
return PartialView("_Tab1", model);
}
...etc
So now we have the _Tabs partial view rendering its own partial views each that can have their very own model.
And when the _Tabs partial is done rendering it will return the HTML to the target div on the main page and have the x number of tabs you have created in the _Tabs.cshtml.
I also was able to keep the current active tab selected with the following script:
<script>
$('#navtab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href").substr(1);
window.location.hash = id;
});
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#navtab a[href="' + hash + '"]').tab('show');
</script>

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

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