Checkbox Constantly Returns False? - javascript

I'm submitting a form using AJAX as follows:
$('#userUpdateForm').submit(function (e) {
//var attachment = $('form#userUpdateForm').serialize();
var blue = document.getElementById('blueCheck').checked;
var personDetails = {
Enabled: $('#eCheck').val(),
Authorised: $('#authCheck').val(),
Green: $('#greenCheck').val(),
Blue: blue,
//Blue: $('input[name="blueCheckbox"]').is(':checked'),
Red: $('#redCheck').val(),
Id: $('#idCheck').val()
};
$.ajax({
type: "POST",
//url: '<%= Url.Action("submitForm", "Home") %>',
url: '#Url.Action("submitForm", "Home")',
data: JSON.stringify({ jsonForm: personDetails}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
'#Url.Action("Index", "Home")';
alert("Success");
},
error: function (result) {
alert("A problem occured when submitting the form.");
}
});
e.preventDefault();
});
'Blue' refers to a checkbox. The form then submits to the controller HomeController/submitForm as below:
public class updatePersonDetails
{
public string Enabled { get; set; }
public string Authorised { get; set; }
public string Green { get; set; }
public bool Blue { get; set; }
public string Red { get; set; }
public string Id { get; set; }
}
[HttpPost]
public ActionResult submitForm(updatePersonDetails personDetails)
{
System.Diagnostics.Debug.WriteLine(personDetails.Blue.ToString());
return View();
}
But 'Blue' persistently returns 'False' when the checkbox has been checked and should return true. As you can see below, I have tried a variety of things to get the value:
var attachment = $('form#userUpdateForm').serialize();
var blue = document.getElementById('blueCheck').checked;
Blue: $('input[name="blueCheckbox"]').is(':checked'),
What's even stranger is the jsonForm on the browser shows 'Blue:true' in the request payload. Is there something I'm missing from getting the proper value on the server side?
Edit: the HTML for the form
<form id="userUpdateForm" method="post">
<fieldset>
<legend>User Details</legend>
<input type="checkbox" name="authorisedCheckbox" value="Authorised" id="authCheck" />Authorised<br />
<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck" />Enabled<br />
</fieldset>
<fieldset>
<legend>Favourite Colours</legend>
<input type="checkbox" name="blueCheckbox" value="Blue" id="blueCheck" />Blue<br />
<input type="checkbox" name="greenCheckbox" value="Green" id="greenCheck" />Green<br />
<input type="checkbox" name="redCheckbox" value="Red" id="redCheck" />Red<br />
<input type="hidden" name="personId" id="idCheck" value='#ViewData["personId"]'>
</fieldset>
<input type="submit" value="Save Changes" name="Save Changes">
<button type="button">Cancel</button>
</form>
There's also a onload function to set the checkboxes to reflect the original data of the person, but I wouldn't have thought that would set the checkbox state as 'False' permanently.
var blueVal = '#ViewData["blue"]';
if (blueVal == "checked") {
document.getElementById("blueCheck").checked = true;
}

On the javascript side you send your data like this:
data: JSON.stringify({ jsonForm: personDetails}),
But your Action signature in the Controller is this:
[HttpPost]
public ActionResult submitForm(updatePersonDetails personDetails)
The default MVC Binder can't bind that together. In the POST your ViewModel is nested in an object with "jsonForm" property, MVC can't match that to the "personDetails" parameter.
You need to either:
Change the JSON property name to match the parameter name in your Action:
data: JSON.stringify({ personDetails: personDetails})
Or just delete the nested property. For simple POSTs there is no need for that. You can just POST your data like this:
data: JSON.stringify(personDetails)
I like this solution more because then it doesn't matter what the parameter name in your action is. The MVC will bind the data solely based on the property names in updatePersonDetails class.

Try to execute same code after removing below statement
e.preventDefault();
For more information about preventDefault please check below link
https://www.w3schools.com/jsref/event_preventdefault.asp
Hope this will help you!

Try this
var blue = $('#blueCheck').is(":checked") ? true : false;

Related

move Employee ID from the selected rows of the table into a hidden List<string> column of the table

I am trying to store the employeeIds from the selected row of the table into the model column EmployeeReinstateVM.selectedEmployeeId from the click event of 'btnUpdate', each id must be stored to EmployeeReinstateVM.selectedEmployeeId. Currently the Ids are stored in to selectedEmployeeId hidden column as array string "23,24,25" So I am trying to store each employee id of the selected rows into the EmployeeReinstateVM.selectedEmployeeId from javascript to send the model into controller post method with selected employeeIds. I am looking for the help from someone. Here is the code
Model Class
public class EmployeeReinstateVM
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public List<string> selectedEmployeeId { get; set; }
public IEnumerable<EmployeeModel> employees { get; set; }
}
Views
<style>
.selectable-row.selected {
background-color: #ddd;
}
</style>
#model EmployeeReinstateVM
foreach (var item in Model.employees)
{
<tr class="selectable-row
#(Model.selectedEmployeeId.Contains(item.EmployeeID.ToString()) ? "selected" :"")"
employee-id="#item.EmployeeID">
<td>#item.EmployeeID</td>
<td>#item.EmployeeName</td>
</tr>
}
<input hidden id="selectedEmployeeId" asp-for="selectedEmployeeId" name="selectedEmployeeId" value="">
<button type="submit" class="btn btn-primary form-control" id="btnUpdate" name="btnActivate" value="update">
Update
</button>
<script type="text/javascript">
$(document).ready(function() {
var employeeIds = [];
$(".selectable-row").click(function() {
$(this).toggleClass("selected");
var employeeId = $(this).attr('employee-id');
if ($(this).hasClass("selected")) {
employeeIds.push(employeeId);
//employeeIds.push($(this).attr('employee-id'));
} else {
employeeIds = employeeIds.filter(function(id) {
return id !== employeeId;
});
}
});
$("#btnUpdate").click(function() {
$("#selectedEmployeeId").val(employeeIds);
console.log($("#selectedEmployeeId").val());
});
})
This seems to be simpler - you need to store the result
$(".selectable-row").click(function() {
$(this).toggleClass("selected");
$("#selectedEmployeeId")
.val(
$("tr[employee-id].selected")
.map(function() { return $(this).attr("employee-id") })
.get()
.join(",")
);
});
store each employee id of the selected rows into the
EmployeeReinstateVM.selectedEmployeeId from javascript to send the
model into controller post method with selected employeeIds
Do you want to try the below code?
$("#btnSave").click(function () {
$("#selectedEmployeeId").val(employeeIds);
console.log($("#selectedEmployeeId").val());
$.ajax({
type: "POST",
url: "/Keepselected/ReinstateEmployee",
data: { "selectedEmployeeId": employeeIds },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
alert(response);
}
});
});
result:

How to pass javaScript value in view page to Controller Action parameter, when change drop down list

I want to pass student Id in my controller action, I used JsonResult action, I catch student id but can't pass in action,
this is my JavaScript code ,
<script type="text/javascript">
$(document).ready(function () {
$("#sId").change(function(){
var studentId = $(this).val();
debugger
$.ajax({
type:"post",
url:"/Department/GetDeptName/" + studentId,
contentType:"html",
success:function(response){
debugger
$("#dId").empty();
$("#did").append(response);
}
})
})
});
</script>
And I have a Dropdown list, I pass my list fron database using ViewBag. When I select a student name then need to pass his/her department name. This is the view code
<div class="row">
<div class="col-md-6 mb-4">
<label asp-for="Name" class="control-label">Student Name</label>
<select asp-for="Id" class="form-control" id="sId"
asp-items="#(new SelectList(#ViewBag.messageStudent,"Id", "Name"))">
</select>
</div>
<div class="col-md-6 mb-4">
<label asp-for="DeptName" class="control-label">Department Name</label>
<input asp-for="DeptName" id="dId" class="form-control mb-3" type="text" placeholder="Dept Name" disabled>
</div>
<input type="hidden" asp-for="Id" name="Id" id="DeptName" />
</div>
This is my controller code that is passed a list from database to View
public async Task<IActionResult> DropDown()
{
var model = _scope.Resolve<FormModel>();
await model.LoadStudenDataAsync();
var studentList = model.StudentList.ToList();
studentList.Insert(0, new Student { Id = 0, Name = "Select Group" });
ViewBag.messageStudent = studentList;
return View(model);
}
Now I need to pass student id from view page, if i pass student id then I solve my problem,
This is my JsonResult Action
public async Task<JsonResult> GetDeptName(int studentId)
{
var model = _scope.Resolve<FormModel>();
if (ModelState.IsValid)
{
await model.DeptList(studentId);
}
return Json(model);
}
Please help me anyone how to pass student id,Thanks in Advance
you have to use get ajax since you are not posting any data in the request body. And change data type to json since you are returning json
$.ajax({
type:"GET",
url:"/Department/GetDeptName/" + studentId,
dataType: 'json',
....
and action
[Route("~/Department/GetDeptName/{studentId}")]
public async Task<JsonResult> GetDeptName(int studentId)
and fix route config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
but if you use old net that doesn't support attribute routing then just change ajax and leave the action as it is now
$.ajax({
type:"GET",
url:"/Department/GetDeptName?studentId=" + studentId,
dataType: 'json',
....

Multiple forms in #foreach loop. How do I submit one asynchronously with javascript. C# core Razor

Shopping cart with many items how to remove any item asynchronously with JavaScript this is my work so far. Can anyone improve on this?
your help would be greatly appreciated. Have a great day
Ok so this works if you remove items from the top of the list but fails if you remove items from some other place.
The problem seems to be that the form names are all the same "remove" without any indexing.
Problem is I'm not sure how to proceed with this.
document.forms['remove'].onsubmit = () => {
let formData = new FormData(document.forms['remove']);
fetch('/sales/cart?handler=RemoveItem', {
method: 'post',
body: new URLSearchParams(formData)
})
.then(() => {
var url = "/sales/cart?handler=CartPartial";
console.log(url)
$.ajax({
url: url,
success: function (data) {
$("#exampleModal .modal-dialog").html(data);
$("#exampleModal").modal("show");
//alert('Posted using Fetch');
}
});
});
return false;
}
<pre>
#foreach (var item in Model.Items)
{
<form name="remove" method="post">
<h4 class="text-left text-body">#item.Price.ToString("c")
<button class="btn btn-sm" title="Trash"><i style="font-size:large"
class="text-warning icon-Trash"></i></button>
</h4>
<input type="hidden" asp-for="#Model.Id" name="cartId" />
<input type="hidden" asp-for="#item.Id" name="cartItemId" />
</form>
}
</pre>
Update
----------
New markup
I added an index to the id and included an onclick event.
<form method="post" id="#i" onclick="removeItem(this.id)">
<button class="btn btn-sm" title="Trash">Item One</button>
<input type="hidden" asp-for="#Model.Id" name="cartId" />
<input type="hidden" asp-for="#item.Id" name="cartItemId" />
</form>
and create a new function that captured the form id including it in a constant.
<script>
function removeItem(formId) {
const form = document.getElementById(formId);
form.onsubmit = () => {
let formData = new FormData(form);
fetch('/sales/cart?handler=RemoveItem', {
method: 'post',
body: new URLSearchParams(formData)
})
.then(() => {
var url = "/sales/cart?handler=CartPartial";
console.log(url)
$.ajax({
url: url,
success: function (data) {
$("#exampleModal .modal-dialog").html(data);
$("#exampleModal").modal("show");
//alert('Posted using Fetch');
}
});
});
return false;
}
}
</script>
If anybody can improve on this please post it here.
Thanks.
Updates code behind Cart.cshtml.cs
using System;
using System.Threading.Tasks;
using Malawby.Models;
using Malawby.Services.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Malawby.Pages.Sales
{
public class CartModel : PageModel
{
private readonly ICartRepository _cartRepository;
public CartModel(ICartRepository cartRepository)
{
_cartRepository = cartRepository ?? throw new
ArgumentNullException(nameof(cartRepository));
}
[BindProperty]
public Cart Cart { get; set; } = new Cart();
public const string SessionKeyName = "_Name";
public string SessionInfo_Name { get; private set; }
public void OnGetAsync()
{
}
public async Task<PartialViewResult> OnGetCartPartialAsync()
{
var userName = GetUserName();
if (userName != null)
{
Cart = await _cartRepository.GetCartByUserName(userName);
}
return Partial("_ToCart", model: Cart);
}
private string GetUserName()
{
return HttpContext.Session.GetString(SessionKeyName);
}
public async Task OnPostRemoveItemAsync(int cartId, int cartItemId)
{
await _cartRepository.RemoveItem(cartId, cartItemId);
}
}
}
Update 2
This is the modified code I used. This is the error in the console.
XML Parsing Error: no root element found Location: localhost:44331/sales/cart?handler=RemoveItem Line Number 1, Column 1
There is no error on the page just nothing happens on the click of the trash can.
<script type="text/javascript">
function removeItem(cartItemId, cardId) {
var removeUrl = "/sales/cart?handler=RemoveItem";
$.post(removeUrl,
{
cartItemId: cartItemId,
cardId: cardId
})
.done(function (data) {
alert(data); //usually return true or false if true
remove card
$('#card_' + cardId).remove();
});
}
</script>
I am not familiar with asp.net core, but I will show how I usually do it without focusing on syntax.
first on the view no need to add multiple form but should use card id as index and delete button sent selected index like this:
#foreach (var item in Model.Items)
{
<div id="card_#item.cardId">
<h4 class="text-left text-body">#item.Price.ToString("c")
<button class="btn btn-sm" onclick="removeItem('#item.cardId') title="Trash"><i style="font-size:large"
class="text-warning icon-Trash"></i></button>
</h4>
</div>
}
then the script function will call remove api and remove selected card with no need to re-render the page:
<script type="text/javascript">
function removeItem(cardId) {
var removeUrl = "your apiUrl";
$.post( "removeUrl", { cardId: cardId })
.done(function( data ) {
alert( data ); //usually return true or false if true remove card
$('#card_'+ cardId).remove();
});
}
</script>

Kendo UI DateTimePicker does not bind properly into the controller

I have a complex object that I need to pass to the controller when submitting a form. This complex object has an object and a list of objects. This is my Web API controller that receives the complex object via post with ajax:
[HttpPost]
public IHttpActionResult CreatePurchaseInvoice(NewPurchaseInvoice newPurchaseInvoice)
{
try
{
var purchaseInvoice = new PurchaseInvoice
{
Id = newPurchaseInvoice.PurchaseInvoice.Id,
DatePurchaseInvoice = newPurchaseInvoice.PurchaseInvoice.DatePurchaseInvoice
};
// Here i do other stuff with the list of objects
_context.SaveChanges();
}
catch(Exception ex)
{
return BadRequest();
}
return Ok();
}
This is my html form:
<form id="purchaseInvoiceForm">
<div class="row">
<div class="col-lg-6">
<label>Order:</label>
<select id="numberOrder" class="form-control" required name="numberOrder">
<option value="">Select an order number...</option>
</select>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Date of Purchase Invoice:</label><br />
<input id="datePurchaseInvoice" style="width: 70%" />
</div>
</div>
</div>
//Here i have an html table and every row i push into an array of the complex object
</form>
And this is my jQuery code where i send the complex object via ajax:
$(document).ready(function(){
//this is the declaration of my complex object
var newPurchaseInvoice = {
PurchaseInvoice: {},
PurchaseInvoiceDetails: []
}
$("#purchaseInvoiceForm").submit(function (e) {
e.preventDefault();
newPurchaseInvoice.PurchaseInvoice= {
Id: $("#numberOrder").val(),
DatePurchaseInvoice : $("#datePurchaseInvoice").val()
}
$.ajax({
url: "/api/purchaseInvoices",
method: "post",
data: newPurchaseInvoice
});
});
});
The problem I have is that the date of the KendoDateTimePicker is not sending correctly to the controller.
I get this date and not the one I select with the kendoDateTimePicker. This is the DatePurchaseInvoice property of my PurchaseInvoice model in spanish:
This is my KendoDateTimePicker for jQuery:
$("#datePurchaseInvoice").kendoDateTimePicker({
value: new Date(),
dateInput: true
});
And this is my NewPurchaseInvoice model:
public class public class NewPurchaseInvoice
{
public PurchaseInvoice PurchaseInvoice{ get; set; }
public List<PurchaseInvoiceDetail> PurchaseInvoiceDetails{ get; set; }
}
This is my PurchaseInvoice model:
public class PurchaseInvoice
{
public int Id { get; set; }
public DateTime DatePurchaseInvoice { get; set; }
}
You need to be specifying the type of data you are supplying:
contentType: 'application/json'
And possibly dataType too depending on your response type. And according to this post, you may need to stringify your response. I don't think I've needed to do that but I don't often use AJAX operations for complicated data types.

How to use POST in ApiController

I have searched for at least an hour and a half now and I'm not any closer to learning how to use POST methods in my ApiController. I need an effective way of using post to create a login system that will search my database based on the username/password combination and create a JSON object that I can send back to my web page. Any resources on using post? I've tried to acomplish this with get but I can use any variables more than 'ID'
public IHttpActionResult GetLogin(string id)
{
//Query Database for Unique username.
if (id == "mager1794")
{
//Create Login class with username, and password details.
return Ok( new Models.Login() { id = 1, userName = "mager1794", passWord = "*******" });
}
return Ok(-1);
}
This is what I have for my Get method but I'm just not having any luck creating a POST version of this.
Maybe something like this:
[RoutePrefix("api/account")]
public class AccountController : ApiController
{
public class LoginInfo
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
}
[Route("login")]
[HttpPost]
public IHttpActionResult AuthenticateUser(LoginInfo loginInfo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!Membership.ValidateUser(loginInfo.Username, loginInfo.Password))
{
ModelState.AddModelError("", "Incorrect username or password");
return BadRequest(ModelState);
}
FormsAuthentication.SetAuthCookie(loginInfo.Username, true);
return Ok();
}
}
Client side:
<form action="#" id="login-form">
<label for="username">Username:</label>
<input type="text" name="username" id="username"/>
<label for="password">Password:</label>
<input type="password" name="password" id="password"/>
<div><input type="submit"/></div>
</form>
<script>
$(document).ready(function () {
$("#login-form").submit(function (e) {
e.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: '/api/account/Login/',
data: { Username: username, Password: password },
success: function () {
// refresh the page if username and password are correct
location.reload();
}
});
});
});
</script>

Categories