I’ve created an array inside a javascript. Now I want to use the array controller. Currently I’m using FormCollection to access data from the form. Is there a way to access my javascript array in FormCollection or as a parameter in the Html.BeginForm()?
I’ve tried doing a JSON post using some examples I found on the forum but the array was null in the controller. Can you please help with the best approach to accessing my javascript array in the controller?
<script type="text/javascript">
var $checkboxes = $('input[type="checkbox"]');
$(document).ready(function () {
$('#saveBtn').click(function () {
var checkList = new Array();
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
checkList.push('checked');
}
else
checkList.push('unchecked');
});
alert(checkList);
});
});
</script>
UPDATE 1
$(document).ready(function () {
$('#saveBtn').click(function () {
var options= [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item={ "UserChoice" : "checked", "OptionID": "YouCanSetIDHere"};
}
else
{
var item={ "UserChoice" : "unchecked", "OptionID": "YouCanSetIDHere"};
}
options.push(item);
}
$.ajax({ type: "POST", url: '#Url.Action("Edit","Attendance")',
contentType: "application/json",
data: JSON.stringify(options)
}).done(function (html) {
//do something with the response.
});
});
});
You can create items which is similar to your viewmodel and push that to your array and post it using jQuery post. In your controller action, you can use a collection of your viewmodel to accept it. MVC model binding will take care of the rest.
Assume you have a ViewModel like this
public class UserOptionVM
{
public string OptionID{ set;get;}
public string UserChoice { set;get;}
}
And in your Action method, you accept a collection of this
[HttpPost]
public ActionResult Save(List<UserOptionVM> model)
{
// loop through collection and read and save
}
Now change your Js file to send something which match with our viewmodel.
var options= [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item={ "UserChoice" : "checked", "OptionID": "YouCanSetIDHere"};
}
else
{
var item={ "UserChoice" : "unchecked", "OptionID": "YouCanSetIDHere"};
}
options.push(item);
});
$.ajax({ type: "POST",
url: "#Url.Action("Save","User")",
contentType: "application/json",
data: JSON.stringify(options)
}).done(function (html) {
//do something with the response.
});
Related
I have a dropdown with selection id StaffId. What I am doing is once an item is selected I want to pass on the StaffId to controller to fetch records in a database using the staffId. This is giving an error on page load without passing the StaffId to the controller. below is the snippet
controller
[HttpPost]
public PartialViewResult GetStaffPosts(int? id)
{
var sPost = db.StaffPosts.Where(a => a.StaffId == id.Value);
return PartialView(sPost.ToList());
}
<div id="divPartialView">
#{Html.RenderPartial("GetStaffPosts");}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
$.ajax(options);
}
});
});
</script>
Your current code is not actually making an ajax call on the change event because you are invoking the $.ajax(options); call inside the success callback of the options object. You are not calling the $.ajax method on the change event!
This should work (assuming your controller code is returning a 200 response).
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
options.type= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
You may also simplify your code using the $.post method.
$("#StaffId").change(function() {
$.post("/StaffPost/GetStaffPosts/",{ id: $(this).val() } ,function (data) {
$("#divPartialView").html(data);
});
});
Or even using the $.load method and a one liner
$("#StaffId").change(function(event) {
$("#divPartialView").load("/StaffPost/GetStaffPosts/", { id: $(this).val() });
});
Hi just put your ajax call outside of the success function and make an url like the below code and try again
Your changed code:
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "../StaffPost/GetStaffPosts,
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest)
{
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
});
</script>
I have a select item as follows:
<select id="id_category">
<option> </option>
</select>
In run time there is a tree view used to fill up the select menu as follows:
<script>
$(document).ready(function () {
$('#data').jstree({
"plugins": ["checkbox"]
});
$("#data").on("changed.jstree", function (e, data) {
if (data.selected.length) {
$("#id_category").empty();
$(data.selected).each(function (idx) {
var node = data.instance.get_node(data.selected[idx]);
var s = document.getElementById('id_category');
s.options[s.options.length] = new Option(node.text, '1');
});
}
else
$("#id_category").empty();
});
});
</script>
and the html for the tree is not important now as it works well.
Now, I want when a user click on a button with HTML as follows:
<input id="btn3" type="button" value="Test 3" />
an ajax will be run to send all the items in the select to a controller in MVC as follows:
$("#btn3").click(function () {
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: $.map($('#id_category')[0].options, function( elem ) { return (elem.value || elem.text); }),
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
and the controller:
[HttpPost]
public string Test03(Object str1)
{
// call with two parameters and return them back
this.myRetrievedData = str1;
return str1.ToString();
}
The above did not work with me, when I click on Test3 button nothing happened.
I am not sure how to pass the retrieved items to the function in the controller. Could anyone tell me how to do that?
The below logic must work for you. Many thanks to Mr.Stephen Muecke for assistance.
$("#btn3").click(function () {
var optionsData= $.map($('#id_category')[0].options, function(elem) {
return (elem.value || elem.text);
}); // create a variable to hold all the options array.
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
Then you can have your controller as below.
[HttpPost]
public string Test03(IEnumerable<string> options ) // change here to this
{
//your logic goes here
}
I think it's because you have not added [HttpPost] attribute in your controller function
I am new to mvc and have been doing lots of looking, but I can't figure out why this isn't working.
I have the following View code:
$(function() {
$("#ddlNumberOfRecords").change(function() {
var numberOfRecords = $("#ddlNumberOfRecords").val();
$.ajax({
type: "POST",
url: '#Url.Action("NumberOfRecordsChanged")',
data: { numberOfRecords: numberOfRecords },
success: function(returndata) {
if (!returndata.ok) {
window.alert(' error : ' + returndata.message);
} else {
$('#Grid').html(returndata);
}
}
});
});
});
#Html.DropDownList("ddlNumberOfRecords", Model.NumberOfRecordsSelectList)
Can someone tell me what is wrong with that? Also, is there a way to debug that javascript? I put breakpoints on there, but they never load.
EDIT: This is my Action. There is no real content yet because I am just trying to get it to work at this point. But I have a breakpoint and it never gets hit.
[HttpPost]
public ActionResult NumberOfRecordsChanged(int numberOfRecords)
{
return null;
}
With everything you shown the code works 100%. I made a mock up to prove just that.
Controller
public ActionResult Index()
{
ViewModel model = new ViewModel
{
NumberOfRecordsSelectList = new List<SelectListItem>
{
new SelectListItem
{
Selected = false,
Text = "one",
Value = "1",
},
new SelectListItem
{
Selected = false,
Text = "two",
Value = "2",
},
}
};
return View(model);
}
[HttpPost]
public ActionResult NumberOfRecordsChanged(int numberOfRecords)
{
return null;
}
View
#model MvcApplication1.Models.ViewModel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#ddlNumberOfRecords").change(function() {
var numberOfRecords = $("#ddlNumberOfRecords").val();
$.ajax({
type: "POST",
url: '#Url.Action("NumberOfRecordsChanged")',
data: { numberOfRecords: numberOfRecords },
success: function (returndata) {
//No return data proviced
//if (!returndata.ok) {
// window.alert(' error : ' + returndata.message);
//} else {
// $('#Grid').html(returndata);
//}
}
});
});
});
</script>
#Html.DropDownList("ddlNumberOfRecords", Model.NumberOfRecordsSelectList)
If you are getting another error than please share how you are creating your list items, what the error is, and any other details relevant to the problem. Thanks.
It seems you're trying to pass over the number of items in the dropdown but are in fact sending over the selected item's value.
If so, this...
var numberOfRecords = $("#ddlNumberOfRecords").val();
Should be this...
var numberOfRecords = $("#ddlNumberOfRecords option").size();
What I have:
A Model like this:
public class ProductModel
{
public string ProductName { get; set; }
public List<string> SkipUpdates { get; set; }
}
A controller method like this:
public ActionResult GetProductUpdates(ProductModel productModel)
{
return View("AddEdit");
}
Not doing anything for now just want to make sure that data from JS comes in correctly.
The JS:
function productModel() {
this.productName = "";
this.SkipUpdates = [];
}
Filling the model and AJAX:
var newProductModel = new productModel();
var options = $('#AdditionalSkipDates option');
var skipDates = [];
options.each(function (i, option) {
skipDates[i] = $(option).text();
});
newProductModel.productName = "ABC";
newProductModel.SkipUpdates = skipDates;
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: newProductModel,
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});
AdditonalSkip dates is a listbox with a bunch of dates in it.
What's happening:
The SkipUpdates array does have values which I can see in the browser's console.
Put a breakpoint in the controller and it hits the method.
The SkipUpdates value is null.
What's not happening:
How do I get the array to come-into the controller?
Thanks in advance.
Try to stringify the object before sending it:
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: JSON.stringify(newProductModel),
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});
I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});