grab value from checkboxes and post as list to controller - c#

Check the code bellow. I am doing post a list of ProductId to my controller and wanted to receive it with view model called- UpdateProductStatus. but the problem with my current code is: ajax post it to controller successfully but the UpdateProductStatus cant grab any value of ProductId. This always returns null. Whats wrong i am doing here? Possibly in ajax i am doing wrong i think. How can i fix this to receive all ProductId as a list form controller? Thanks in advance
Controller:
[HttpPost]
public IActionResult UpdateProductStatus([FromBody]List<UpdateProductStatus> UpdateProductStatus)
{
return Json("ok");
}
View Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlexzWeb.ViewModels
{
public class UpdateProductStatus
{
public int ProductId { get; set; }
}
}
Jquery:
$('#btnActivate').on('click', function () {
var allSelectedProductId = [];
var allSelectedProductIdWithKey = [];
$('.chkItems:checked').each(function() {
allSelectedProductId.push($(this).val());
});
for (var _allSelectedProductId in allSelectedProductId) {
allSelectedProductIdWithKey.push('ProductId'+':'+_allSelectedProductId);
}
console.log(allSelectedProductIdWithKey);
//var things = JSON.stringify(allSelectedProductIdWithKey);
var things = JSON.stringify({ 'UpdateProductStatus': allSelectedProductIdWithKey });
console.log(things);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Products/UpdateProductStatus',
data: things,
success: function () {
console.log('sssss');
},
failure: function (response) {
console.log('fffff');
}
});
Html:
<input type="checkbox" class="chkItems" value="1">
<input type="checkbox" class="chkItems" value="2">
<button id="btnActivate">Button</button>

Your current code is sending a payload like below for the ajax call.
{"UpdateProductStatus":["ProductId:0","ProductId:1"]}
Your action method argument is a list of UpdateProductStatus objects. So for model binding to work properly with your current action method parameter signature, your payload should be like below.
[{"ProductId":"1"},{"ProductId":"2"}]
There is no need to specify the parameter name. Just pass an array of items, each with a ProductId property and it's value.
var allSelectedProductIdWithKey = [];
$('.chkItems:checked').each(function () {
allSelectedProductIdWithKey.push({ ProductId: $(this).val() });
});
var things = JSON.stringify(allSelectedProductIdWithKey);
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: '/Products/AppendClientFilter',
data: things,
success: function (res) {
console.log('Successs', res);
},
failure: function (response) {
console.log('Error', response);
}
});
You can also remove the dataType in ajax call. jQuery ajax will guess the proper type from the response header and in your case you are going to return explicitly JSON.

To bind to your controller method, you need to send an array of objects containing a name/value pair for ProductId. To build your array of objects, use
$('#btnActivate').on('click', function () {
var allSelectedProductId = [];
$('.chkItems:checked').each(function() {
allSelectedProductId.push({ ProductId: $(this).val() });
});
var things = JSON.stringify({ UpdateProductStatus: allSelectedProductId });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Products/UpdateProductStatus',
data: things,
success: function () {
....
});
});

Related

MVC Ajax: How to send string from view to controller

I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}

Why the parameter being passed to the controller method from jquery is null even it's not?

I have been trying to call my .cs method in the controller from jquery json and it gets called but the parameter passed is always null. Why? Even i checked in the console log and it shows the value being passed but somehow it doesn't get passed to the method. It's null.
$('#AppointmentDate').change(function () {
var AppointmentDate = '2018-04-30'; //document.getElementById('AppointmentDate').value;
$.ajax
({
url: '#Url.Action("GetTimeSlotsByDate", "Appointment")',
type: 'GET',
contentType: "application/json; charset= utf-8",
data: JSON.stringify(AppointmentDate),
dataType: 'json',
success: function (results) {
$("#fk_TimeSlotID").html(""); // clear before appending new list
$.each(results, function (i, slot) {
$("#fk_TimeSlotID").append(
$('<option></option>').val(slot.TimeSlotID).html(slot.FromTo));
});
console.log('Time slots returned');
console.log(AppointmentDate);
}
});
Method:
public ActionResult GetTimeSlotsByDate(DateTime? RequestedAppointmentDate)
{
TimeSlotsRepository TimeSlotsRep = new TimeSlotsRepository();
List<TimeSlotsModel> ListTimeSlotsModel = TimeSlotsRepository.getTimeSlotsByDate(RequestedAppointmentDate);
return Json(ListTimeSlotsModel, JsonRequestBehavior.AllowGet);
}
This is the rendered URL
http://localhost:13924/Appointment/GetTimeSlotsByDate?"2018-04-30"
You can convert your data to query string parameters and pass to server in
url as
somesite.com/Appointment/GetTimeSlotsByDate?RequestedAppointmentDate=your date
try this ,Its working for me
$('#AppointmentDate').change(function () {
// var AppointmentDate = '2018-04-30'; //document.getElementById('AppointmentDate').value;
$.ajax
({
url: '#Url.Action("GetTimeSlotsByDate", "Appointment")',
type: 'GET',
contentType: "application/json; charset= utf-8",
//data: JSON.stringify(AppointmentDate),
data: { RequestedAppointmentDate: "2018-04-30" },
dataType: 'json',
success: function (results) {
$("#fk_TimeSlotID").html(""); // clear before appending new list
$.each(results, function (i, slot) {
$("#fk_TimeSlotID").append(
$('<option></option>').val(slot.TimeSlotID).html(slot.FromTo));
});
console.log('Time slots returned');
console.log(AppointmentDate);
}
});

Passing arguments in jQuery post to a method in controller

In ASP.NET MVC I was using this script to call a method in controller:
<script>
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: "2",
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
</script>
and this is the method I call:
public async Task getBookedByUser(string id)
{
BenchesService benchService = new BenchesService();
List<Bench> obj = await benchService.getLastBenchByUser(id);
userBench = obj.ElementAt(0);
}
My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.
Any idea why?
You're almost there. You need to setup the JSON to include your id property:
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: { id: '2' },
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});

Ajax POST not posting list

I am passing data to controller through Ajax call.
Following is the ajax code:
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List[i] = $(selectedItem).text();
});
var from_Month = $("#fromKPAMonthPicker").val();
var from_Year = $("#fromKPAYearPicker").val();
var to_Month = $("#toKPAMonthPicker").val();
var to_Year = $("#toKPAYearPicker").val();
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
success: function (data) {
$("#divList").html(data);
}
});
Controller action method:
[HttpPost]
public ActionResult _DataByFromTo(List<Int32> doj_Month_List, Int16 from_Month, Int16 from_Year, Int16 to_Month, Int16 to_Year)
{
return View();
}
It was working in my old code perfectly fine. I don't know whats the problem. because all data are passing perfectly except this array of jquery.
To disable deep serialization of objects you need to set traditional property to true.
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
traditional: true,
success: function (data) {
$("#divList").html(data);
}
});
When set to true it results in a shallow serialization.
Following link might be of help.
https://api.jquery.com/jQuery.param/
try using push
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List.push($(selectedItem).text());
});

What is wrong with this JQuery AJAX code

I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },

Categories

Resources