Ajax refreshing page in MVC - c#

I'm using Ajax to pass some data to a Controller and save to database, and it works, the issue that is refreshing the page with every POST and I need to prevent that.
Ajax:
function AddComment(commet, auto) {
$.ajax({
type: "POST",
url: '/bff/SaveComment',
data: { id: idParte, commenta: commet, autoriza: auto },
dataType: 'json',
success: function (correct) {
$("#win1").show().kendoWindow({
width: "300px",
height: "100px",
modal: true,
title: "Added"
});
},
errror: function(inc) {
}
});
}
Controller:
[HttpPost]
public JsonResult SaveComment(int id, string commenta, string autoriza)
{
// Some logic here
return Json("");
}
Tried this way with correct.preventDefault(); but didn't work
Is there a way to do it?
EDITED:
This is my HTML:
<form role="form">
<div class="form-group">
#Html.Label("Commentario:")
<textarea id="Comment" style="resize:none;" class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" value="Guardar" onclick="AddComment(Comment.value,'Comentario')" />
</div>
</form>
EDITED 2:
Fixed by changing type="submit" for type="button" Thanks to Hasta Pasta

i think you should put return false; after the ajax request
function AddComment(commet, auto) {
$.ajax({
type: "POST",
url: '/bff/SaveComment',
data: { id: idParte, commenta: commet, autoriza: auto },
dataType: 'json',
success: function (correct) {
$("#win1").show().kendoWindow({
width: "300px",
height: "100px",
modal: true,
title: "Added"
});
},
error: function(inc) {
}
});
return false;
}
based on you need to return false as you sayed :)
<form role="form">
<div class="form-group">
#Html.Label("Commentario:")
<textarea id="Comment" style="resize:none;" class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" value="Guardar" onclick="return AddComment(Comment.value,'Comentario')" />
</div>
</form>

Related

FormData not binding values to controller

I have an Asp.net core application in which I have a form. When I click on the submit button I am using jquery ajax post to submit the form. I am facing 2 problems here,
When I press the submit button, the client side validations are not happening and the form is being submitted.
I have a Break point in the SendEmail Method, and for some reason the FormData binds all null values to the object. Please help.
Here is my form
<form name="ajax-form" id="formPostComment" enctype="multipart/form-data" method="post">
<div class="col-sm-6 contact-form-item wow zoomIn">
<input name="name" id="name" type="text" placeholder="Your Name: *" required/>
<span class="error" id="err-name">please enter name</span>
</div>
<div class="col-sm-6 contact-form-item wow zoomIn">
<input name="email" id="email" type="text" placeholder="E-Mail: *" required/>
<span class="error" id="err-email">please enter e-mail</span>
<span class="error" id="err-emailvld">e-mail is not a valid format</span>
</div>
<div class="col-sm-6 contact-form-item wow zoomIn">
<label for="myfiles">Select file (If Any):</label>
<input name="attachment" id="attachment" type="file" />
</div>
<div class="col-sm-12 contact-form-item wow zoomIn">
<textarea name="message" id="message" placeholder="Your Message" required></textarea>
</div>
<div class="col-sm-12 contact-form-item">
<input class="send_message btn btn-main btn-theme wow fadeInUp" type="submit" id="submit" name="submit" data-lang="en" onclick="SendEmail();"></input>
</div>
<div class="clear"></div>
<div class="error text-align-center" id="err-form">There was a problem validating the form please check!</div>
<div class="error text-align-center" id="err-timedout">The connection to the server timed out!</div>
<div class="error" id="err-state"></div>
</form>
<script>
function SendEmail() {
var formData = new FormData();
formData.append("Name", $("#name").val());
formData.append("Email", $("#email").val());
formData.append("Attachment", $("#attachment")[0]);
formData.append("Message", $("#message").val());
alert($("#name").val());
$.ajax({
type: 'POST',
url: "/Home/SendEmail",
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (response) {
alert("Done");
$('#formPostComment')[0].reset();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
//}).done(function (data) {
// console.log(data);
// $("#ajaxwaiting").hide();
// $("#ajaxsuccess").show();
//});
event.preventDefault();
}
</script>
Here is my Controller action method.
[HttpPost]
public IActionResult SendEmail([Bind("Name,Email,Attachment,Message")] SingleEmailMessage message)
{
return Json(new { data = "DONE" });
}
The SingleEmailMessage class is as follows,
public class SingleEmailMessage
{
public string Name { get; set; }
public string Email { get; set; }
public IFormFile Attachment { get; set; }
public string Message { get; set; }
}
you might be sending two POSTs here... don't use onclick on the submit... instead use onsubmit on the form tag... ex:
<form ... onsubmit="SendEmail(); return false;"> Don't forget the "return false;" bit that replaces your event.preventDefault() call. It's also easier to pass the form's ID into your function... so
SendEmail("formPostComment")... then function SendEmail(id) {
...
thisForm = document.getElementById(id);
var formData = new FormData(thisForm);
On controller side get the file by using:
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
}
Not sure that the file is going to bind to your model.... get it from the raw request.
The full JS function I use is this (just for reference):
//for uploads
function PostFileFormID(id, buttonid, destURL) {
$('#' + buttonid).attr('value', "Uploading...");
thisForm = document.getElementById(id);
var formData = new FormData(thisForm);
jQuery.ajax({
type: 'POST',
url: destURL,
data: formData,
processData: false,
contentType: false,
success: function (data) {
params = convertJsonToParams(data);
url = "?" + params;
setLocation(url);
},
error: function (jqXHR, textStatus, error) {
DisplaySuperError(jqXHR, textStatus, error);
}
});
}

AJAX parameter still null

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.

How to handle a form that have next and previous buttons with one submit button

I have a pop up that have a questions for the user,when the user answer first question and click next the second question will appear and so on , I want to submit this form once the user answer all these question and click the last next button ,
Can i handle that with one submit button?
In the following an example to show how to make a wizard, the example is limited on two views (FirstView and SecondView), it is done with Notepad and remains to test it.
Index View
#model namespace.MyModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<head>
<script type="text/javascript">
$("#StartWizardButton").on("click", ShowWizard('FirstParamerValue'));
function ShowWizard(parameter) {
$.ajax({
url: '#Url.Action("FirstViewAction", "HomeController")',
type: "GET",
data:{model:JSON.Parse(#Html.Raw(Json.Encode(Model)))},
success: function (response, status, xhr) {
$('#WizardModalContainer').html(response);
$('#WizardModalDiv').modal({ backdrop: 'static', keyboard: false });
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
</head>
<body>
<button id="StartWizardButton" type="submit" data-toggle="modal">Start Wizard</button>
............
<div class="modal fade container" id="WizardModalDiv" tabindex="1" role="dialog" aria-hidden="true">
<div class="modal-dialog" id="Wizard-modal-dialog">
<div class="modal-content" id="WizardModalContent">
<div class="modal-header" id="WizardModalHeader"></div>
<div class="modal-body" id='WizardModalContainer'>
</div>
<div class="modal-footer" id="WizardModalFooter">
<button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
<button type="button" onclick="ShowWizard(); return false;" class="btn btn-primary">Next</button>
</div>
</div>
</div>
</div>
</body>
First View
#model namespace.FirstModel
<head>
<script type="text/javascript">
$("#SecondViewWizardButton").on("click", ShowSecondView());
function ShowSecondView() {
$.ajax({
url: '#Url.Action("SecondViewAction", "HomeController")',
type: "GET",
data:{model:JSON.Parse(#Html.Raw(Json.Encode(FirstModel)))},
success: function (response, status, xhr) {
$('#WizardModalContainer').html(response);
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
</head>
<body>
<button id="SecondViewWizardButton" type="submit" data-toggle="modal">Next</button>
............
</body>
Second View
#model namespace.SecondModel
<head>
<script type="text/javascript">
$("#SecondView").on("click", ShowSecondView());
function ShowSecondView() {
$.ajax({
url: '#Url.Action("SecondViewAction", "HomeController")',
type: "GET",
data:{model:JSON.Parse(#Html.Raw(Json.Encode(SecondModel)))},
success: function (response, status, xhr) {
$('#WizardModalDiv').modal('hide');
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
</head>
<body>
<button id="SecondViewWizard" type="submit" data-toggle="modal">Next</button>
............
</body>
The Controller
public class CommandeController : Controller
{
public ActionResult Index()
{
return View("Index", MyModel);
}
public PartialViewResult FirstViewAction(MyModel model)
{
............
return PartialView("FirstView", FirstModel);
}
public PartialViewResult SecondViewAction()
{
...........
return PartialView("SecondView", SecondModel);
}
}
Cordially

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