AJAX parameter still null - c#

I have a simple modal form used to insert data; when i submit data, i correctly go to my method but the parameter still null value.
This is my Razor code:
<form id="SaveKeyForm" asp-page-handler="SaveExternalKEY" data-ajax="true" data-ajax-method="post">
<div class="modal-body">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<div class="form-group">
<label asp-for="wItem.Guid"></label>
<input asp-for="wItem.Guid" name="GUID" class="form-control" id="modalCustomerGUID" readonly required />
<span asp-validation-for="wItem.Guid" class="text-danger"></span>
</div>
<div class="form-group">
#Html.Hidden("External_Key_Type_ID", "")
<select class="custom-select mr-sm-2" asp-items="_KeyOptions" name="Selected_Key_Type_ID"><option selected>Choose</option></select>
</div>
<div class="form-group">
<label asp-for="wExternal_ID.ExternalKey"></label>
<input asp-for="wExternal_ID.ExternalKey" name="ExternalKEY" class="form-control" required/>
<span asp-validation-for="wExternal_ID.ExternalKey" class="text-danger"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="saveKey" class="btn btn-primary">Save</button>
</div>
This is my JS code:
$("#saveKey").click(function (e) {
e.preventDefault();
console.log('Ajax submit');
var form = $(this).parents('.modal').find('form');
var formAction = form.attr('action');
var fdata = form.serialize();
console.log(fdata);
var sdata = { GUID: 'fdsfas' };
$.ajax({
type: 'post',
url: formAction,
data: sdata,
dataType: "text",
processData: false,
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
statusCode: {
404: function () {
console.log("page not found");
},
200: function () {
console.log("Status Ok");
}
}
}).done(function (result) {
console.log('Result: ' + result);
});
});
and this is my method:
public IActionResult OnPostSaveExternalKEY(string GUID)
{
try
{
return new OkResult();
}
catch (Exception ex)
{
return new StatusCodeResult(404);
}
}
}
i have try to:
- pass data as 'fdata' variable: still null
- pass fixed data as 'sdata' variable: still null
- try to Json serialize: still null
If i use jquery-ajax-unobtrusive, i can pass correctly value to my method, but i cannot manage error message in modal form and url change.
Thanks for any help.

Related

Call the same function

I would like whichever button been clicked I want to call the same function.
for now I have six card on View but work only one first. Other dosent work
My view
<h2>Our workouts</h2>
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img src="~/Content/not-found-image.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
#*Go to anywhere*#
<a id="btnNewSave" class="btn btn-primary">Go to anywhere</a>
<input type="text" id="getValue" value="#item.Id" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
My controller:
[HttpGet]
public ActionResult ListCoach(int? Id)
{
var ChoachList = _TraningService.Coach(Id);
return View(ChoachList);
}
script
I call My script from View use helper section
#section scripts {
<script>
$(document).ready(function () {
$("#btnNewSave").click(function () {
var data = $("#getValue").val();
$.ajax({
type: "GET",
url: '/TrainingType/ListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/TrainingType/ListCoach';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
});
});
</script>
}
You should try this way, because your type of buttons are diffrent as per current scenario <a> and button so below way you could try.
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function PassToContoller(data) {
//alert(data);
$.ajax({
type: "GET",
url: '/UserLog/AnotherListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/appUser/ManageAccount';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
$(document).ready(function () {
$("a[name=link]").on("click", function () {
var valueOfClickedTag = $(this).data("index");
alert("Clicked On Anchor: " + valueOfClickedTag);
var callFunc = PassToContoller(valueOfClickedTag)
});
$(":button[id=GoToAnywhere3]").on("click", function () {
var valueOfClickedBtn = $(this).data("index");
var callFunc = PassToContoller(valueOfClickedBtn )
});
});
</script>
}
Razor HTML:
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
#*<img src="~/Content/no_foto.png" class="card-img-top" alt="...">*#
<div class="card-body">
<h5 class="card-title">#item.StudentID</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
Go to anywhere
<a class="btn btn-primary" data-index="#item.Name" name="link">Go to anywhere</a>
<input class="btn btn-primary" type="button" id="GoToAnywhere3" data-index="#item.StudentID" value="Save" />
<input type="text" class="inputVal" id="getValue" value="#item.Name" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
Output:
Note: <input type="text" class="inputVal" id="getValue" value="#item.StudentID" hidden /> is not needed anymore.
Hope it would completely resolve your problem.
Firstly make use of button type rather than an a. With that change, you can use the onclick event in two ways:
First opt:
<button class="btn btn-primary list-coaches" onclick="listCoaches()">List Coaches</button>
function listCoaches() { ... }
Second opt:
<button class="btn btn-primary list-coaches">List Coaches</button>
$('.list-coaches').click(function() { ... });

Sending view model by ajax to controller - how does it really work?

I can't understand why, sometimes sending object by ajax works and sometimes it doesn't. I have an example - everything happens in 1 view where I have 2 view components
1st - view of view component
#model ShippingViewModel
<input type="hidden" name="step" value="#ShoppingCartHelper.TokenShipping" />
<input type="hidden" asp-for="CustomerId" />
<div class="form-group">
<label asp-for="FirstName" class="m-1"></label>
<div><span asp-validation-for="FirstName" class="text-danger"></span></div>
<input asp-for="FirstName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="LastName" class="m-1"></label>
<div><span asp-validation-for="LastName" class="text-danger"></span></div>
<input asp-for="LastName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Email" class="m-1"></label>
<div><span asp-validation-for="Email" class="text-danger"></span></div>
<input asp-for="Email" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Address" class="m-1"></label>
<div><span asp-validation-for="Address" class="text-danger"></span></div>
<input asp-for="Address" class="form-control" />
</div>
<div class="form-group">
<label asp-for="AddressNumber" class="m-1"></label>
<div><span asp-validation-for="AddressNumber" class="text-danger"></span></div>
<input asp-for="AddressNumber" class="form-control" />
</div>
<div class="form-group">
<label asp-for="City" class="m-1"></label>
<div><span asp-validation-for="City" class="text-danger"></span></div>
<input asp-for="City" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ZipCode" class="m-1"></label>
<div><span asp-validation-for="ZipCode" class="text-danger"></span></div>
<input asp-for="ZipCode" class="form-control" />
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="isTheSame">
<label class="form-check-label" for="isTheSame">Czy dane płatnika mają być takie same jak dane wysyłki?</label>
</div>
<button class="btn" id="save-shipping">Dalej <i class="fa fa-level-down" aria-hidden="true"></i></button>
<script type="text/javascript">
$(document).ready(function () {
$('#save-shipping').on('click', function () {
var ShippingViewModel = {
CustomerId: $('input[name="CustomerId"]').val(),
FirstName: $('input[name="FirstName"]').val(),
LastName: $('input[name="LastName"]').val(),
Email: $('input[name="Email"]').val(),
Address: $('input[name="Address"]').val(),
AddressNumber: $('input[name="AddressNumber"]').val(),
City: $('input[name="City"]').val(),
ZipCode: $('input[name="ZipCode"]').val(),
IsTheSame: $('input[id="isTheSame"]').is(':checked'),
};
$.ajax({
type: "POST",
url: '/koszyk/cs',
data: JSON.stringify(ShippingViewModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
error: function (xhr) {
if (xhr.status != 200) window.location.href = "/home/error/" + xhr.status;
},
complete: function (xhr) {
if (xhr.responseText.includes('#ShoppingCartHelper.TokenShipping')) {
$('#ShoppingCartCustomerShipping').html(xhr.responseText);
} else if (xhr.responseText.includes('#ShoppingCartHelper.TokenBilling')) {
$('#ShoppingCartCustomerShipping').hide();
$('#ShoppingCartCustomerBilling').html(xhr.responseText);
}
}
});
});
});
</script>
1st - action in controller
[HttpPost]
[ValidateAntiForgeryToken]
[Route(RouteUrl.ShoppingCart + "/cs")]
public IActionResult Shippping([FromBody] ShippingViewModel svm)
and above code works great - I'm receving ShippingViewModel
and then at the same view I have 2nd view component
2nd - view of view component / the same approach
#model BillingViewModel
#if ((Model.BillingSteps != (int)CustomerModel.StepEnum.None) && (Model.BillingSteps == (int)CustomerModel.StepEnum.Shipping))
{
#Html.Raw("<div style=\"display:block;\">")
}
else
{
#Html.Raw("<div style=\"display:none;\">")
}
<input type="hidden" value="#ShoppingCartHelper.TokenBilling" />
<input type="hidden" asp-for="BillingCustomerId" />
<div class="form-group">
<label asp-for="BillingFirstName" class="m-1"></label>
<div><span asp-validation-for="BillingFirstName" class="text-danger"></span></div>
<input asp-for="BillingFirstName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="BillingLastName" class="m-1"></label>
<div><span asp-validation-for="BillingLastName" class="text-danger"></span></div>
<input asp-for="BillingLastName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="BillingEmail" class="m-1"></label>
<div><span asp-validation-for="BillingEmail" class="text-danger"></span></div>
<input asp-for="BillingEmail" class="form-control" />
</div>
<div class="form-group">
<label asp-for="BillingAddress" class="m-1"></label>
<div><span asp-validation-for="BillingAddress" class="text-danger"></span></div>
<input asp-for="BillingAddress" class="form-control" />
</div>
<div class="form-group">
<label asp-for="BillingAddressNumber" class="m-1"></label>
<div><span asp-validation-for="BillingAddressNumber" class="text-danger"></span></div>
<input asp-for="BillingAddressNumber" class="form-control" />
</div>
<div class="form-group">
<label asp-for="BillingCity" class="m-1"></label>
<div><span asp-validation-for="BillingCity" class="text-danger"></span></div>
<input asp-for="BillingCity" class="form-control" />
</div>
<div class="form-group">
<label asp-for="BillingZipCode" class="m-1"></label>
<div><span asp-validation-for="BillingZipCode" class="text-danger"></span></div>
<input asp-for="BillingZipCode" class="form-control" />
</div>
<button class="btn" id="save-billing">Dalej <i class="fa fa-level-down" aria-hidden="true"></i></button>
<script type="text/javascript">
$(document).ready(function () {
$('#save-billing').on('click', function () {
var BillingViewModel = {
BillingCustomerId: $('input[name="BillingCustomerId"]').val(),
BillingFirstName: $('input[name="BillingFirstName"]').val(),
BillingLastName: $('input[name="BillingLastName"]').val(),
BillingEmail: $('input[name="BillingEmail"]').val(),
BillingAddress: $('input[name="BillingAddress"]').val(),
BillingAddressNumber: $('input[name="BillingAddressNumber"]').val(),
BillingCity: $('input[name="BillingCity"]').val(),
BillingZipCode: $('input[name="BillingZipCode"]').val(),
};
console.log(BillingViewModel);
$.ajax({
type: "POST",
url: '/koszyk/cb',
data: JSON.stringify(BillingViewModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
error: function (xhr) {
if (xhr.status != 200) window.location.href = "/home/error/" + xhr.status;
},
complete: function (xhr) {
if (xhr.responseText.includes('#ShoppingCartHelper.TokenBilling')) {
$('#ShoppingCartCustomerBilling').html(xhr.responseText);
} else if (xhr.responseText.includes('#ShoppingCartHelper.TokenPayment')) {
$('#ShoppingCartCustomerBilling').hide();
$('#ShoppingCartCustomerPayment').html(xhr.responseText);
}
}
});
});
});
</script>
#Html.Raw("</div>")
2nd - action in controller
[HttpPost]
[ValidateAntiForgeryToken]
[Route(RouteUrl.ShoppingCart + "/cb")]
public IActionResult Billing([FromBody] BillingViewModel bvm)
and here - I'm receving BillingViewModel - null
and I dont understand WHY firt ajax call sending a model, and second dosent
I found a workaround - insted of [FromBody] BillingViewModel bvm I cound [FromBody] object bvm
and then I cound deserialized bvm - and its working
Question
What exacly I do wrong? it turns out that I don't understand how ajax works in asp core. I don't see any errors in my code.
EDIT:
Model
public int BillingCustomerId { get; set; }
public string BillingFirstName { get; set; }
public string BillingLastName { get; set; }
public string BillingAddress { get; set; }
public string BillingAddressNumber { get; set; }
public string BillingZipCode { get; set; }
public string BillingCity { get; set; }
public string BillingEmail { get; set; }
public int BillingSteps { get; set; }
sending data
screen of sending data

I'm getting a 500 status code response when I update ajax ASP.NET MVC

I want to update my user information but I'm getting an error
500 status code response
when I'm updating my data.
This is my code:
Context class:
public void Update(UserInformation model)
{
var user = _db.UserInfo
.FirstOrDefault(m_id => m_id.Id == model.Id);
_db.Update(user);
_db.SaveChanges();
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> PostEdit(UserInformation userInformation)
{
if (!ModelState.IsValid)
{
}
_ui_context.Update(userInformation);
return new JsonResult("User Updated!");
}
My AJAX call:
if (action == "Update") {
$.ajax({
method: "POST",
url: "/UserInformation/PostEdit",
data: $('#form_data').serialize(),
dataType: "JSON",
success: function (data) {
alert(data);
clearFields();
$("#exampleModal").modal("hide");
loadUser();
}
});
}
Then this is my view on modal:
<form method="POST" id="form_data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<input type="hidden" id="action_value" value="" />
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" id="txtFirst" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" id="txtLast" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Location" class="control-label"></label>
<input asp-for="Location" class="form-control" id="txtLocation" />
<span asp-validation-for="Location" class="text-danger"></span>
</div>
</form>
This is the error I am getting:
Thank you for your answer! Appreciate it much
The 500 status that mean there is exception inside PostEdit() action. Please check your model userInformation pass into method _ui_context.Update(userInformation);
You can change
if (!ModelState.IsValid)
{
return new JsonResult("Model is invalid");
}

Passing and handling of varibles to a function with AJAX in MVC

I'm having trouble passing a variable into a function in my view. I'm fairly new to MVC and not sure how I save and pass information.
#model Models.Schedule.SheduleModel
#{
Layout = null;
}
<div>
<div class="tableRow">
<p>Make a schedule reminder.</p>
</div>
<div class="tableRow tableRowHeading">
<div class="row" style="width: 210px">Name</div>
<div class="row" style="width: 210px">Number</div>
</div>
#foreach (var shedule in Model.ScheduleList)
{
<div class="tableRow">
#using (Html.BeginForm("UpdateSchedule", "Schedule", FormMethod.Post))
{
<div class="cell" style="width: 210px">
#Html.HiddenFor(model => schedule.Id)
#Html.TextBoxFor(model => schedule.Name, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => schedule.Name)
</div>
<div class="cell" style="width: 210px">
#Html.TextBoxFor(model => agent.ContactNumber, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => agent.ContactNumber)
</div>
<div class="cell">
<button name="Update" type="submit" value="Update" class="button" title="Update details">
<span class="text">Update</span>
</button>
</div>
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule();" value="Delete">
<span class="text">Delete</span>
</button>
</div>
}
</div>
}
</div>
#Scripts.Render("~/bundles/jqueryval")
<script>
function deleteFromSchedule() {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + Id,
data:
{
Id: Id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>
I'm trying to pass the schedule Id in HiddenFor into the delete function but everything I try doesn't work, i'm also curious on how to handle the information gotten from the text box in a later unwritten div, I'd like to produce text on the screen saying
User #Model.Name and number #Model.Number will be notified of schedule change but I keep displaying blank spaces. an I use the form I'm creating for this information, what would the syntax be?. My method in the schedule controller is very straight forward.
[HttpPost]
public void UpdateSchedule(int Id)
{
////do stuff here
}
The simplest way is to add your id from the schedule into the inline function call (using razor), and add an id param into your javascript delete function:
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule(#schedule.Id);" value="Delete">
<span class="text">Delete</span>
</button>
</div>
<script>
function deleteFromSchedule(id) {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + id,
data:
{
Id: id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>

Pass data from html form to c# webservice using ajax

I have a form html made using bootstrap in phpstorm, and I want to pass the information to a c# webservice using ajax.
Bust I have some doubts in what to put in the ajax url (represented bellow).
This is my html/bootstrap form:
<form role="form" action="" method="post" class="login-form">
<div class="form-group">
<label class="sr-only" for="form-username">Email</label>
<input type="text" name="form-username" placeholder="Email....." class="form-username form-control" id="form-email">
</div>
<div class="form-group">
<label class="sr-only" for="form-text">Type Order</label>
<input type="text" name="order" placeholder="Tipo Encomenda" class="form-text form-control" id="textbox1">
</div>
<span id="spnGetdet" style="font-size:x-large" />
<div class="form-group">
<label class="sr-only" for="form-number">Number</label>
<input type="number" min="0" max="150" name="orderQuantity" placeholder="Numero Peças" class="form-number form-control" id="form-number">
</div>
<div class="form-group">
<label class="sr-only" for="form-radio">Urgente</label>
<label class="radio-inline">
<input type="radio" name="optradio">Urgente</label>
<label class="radio-inline">
<input type="radio" name="optradio">Não Urgente
</label>
</div>
<button type="submit" class="btn btn-primary" id="submitOrder">Enviar</button>
</form>
And this is my ajax/jquery code:
<script type="text/javascript">
$("#submitOrder").click(function(){
$(document).ready(function () {
var TextBox1 = $("#textbox1");
TextBox1.change(function (e) {
var Name = TextBox1.val();
if (Name != -1) {
Getdet(Name);
}else {
<?php echo "erro"?>;
}
});
});
}
function Getdet(Name) {
$.ajax({
type: "POST",
url: "",
data: "{'Custname':'" + Name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response){
$("#spnGetdet").html(response.d);
},
failure: function (msg)
{
alert(msg);
}
});
}
</script>
And the last my c# webservice (this is a test, and i only want to collect the type of the order):
[WebMethod]
public String GetCustdet(string Custname)
{
return Custname;
}
So, if i have the project(website) made in phpstorm and webservice visual studio, what do I have to put in the url of ajax to reach the web service???
P.S: WebSite running in xampp
I'm assuming that, you are using MVC pattern I have given following url. You should replace controller name in [controller] place. You should replace localhost:5566 in or whatever in to [server-name].
option 1: [GET] http://[server-name]/[controller]/GetCustdet?Custname=Jhon
without data.
option 2: [POST] http://[server-name]/[controller]/GetCustdet
with data: '{Custname:"Jhon"}'
Otherwise, If you are using Asp.Net template to create the WebMethod then you should use the aspx page name in place the of [controller].
Alternatively, you have Route configurations to customize the URL and the data.

Categories