How to get rid of this ajax form posting issue? - asp.net-mvc-3

I am posting a form to controller action. I am getting an error from the controller.
This is the behavior I want:
If error - show the right error message on the same page without any page refresh.
If success - show the success message on the page again no page refresh
what I am getting is that the page gets fully refreshed with different url and shows this:
{"status":"Failed","msg":"\u0027Name\u0027 "}
The url changes to this: ../respond/update which is the action I post to
Basically I want to catch this Failed status and display the msg inside a span.
But why it is taking me to a different page?
Here is the view:
#using (Html.BeginForm("Update", "Respond", FormMethod.Post, new { id = "frmUpdate" }))
{
//have my form here
//submit button
}
Here is the js handler that posts the form:
$('#frmUpdate').submit(function () {
//validation
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
beforeSend: //show loader
success: function (result) {
alert(result.status);
},
error: function (xhr, status, error) { alert('error'); }
});
return false;
});
Here is controller:
[HttpPost]
public ActionResult Update(ResponseModel model)
{
return Json(new { status="Failed", msg = "Name" });
}
EDIT:
In Firefox it takes to differnt url.
But in IE8 I get this error from jquery itself. Interesting...
Message: Object doesn't support this property or method
Line: 28
Char: 12724
Code: 0
URI: /Content/js/external/jquery-1.6.2.min.js?v=3

I think you should stop the default submit behavior by doing so:
$('#frmUpdate').submit(function (e) {
e.preventDefault();
<your code here>
});
Otherwise the form submit will happen causing the behaviour you want to avoid.
Hope this helps.

#using (Html.BeginForm("Update", "Respond", FormMethod.Post, new { id = "frmUpdate" }))
{
//have my form here
//submit button
}
If you are using submit button than it will post the page. You need to use type button instead of submit.
It will work.
#using (Html.BeginForm("Update", "Respond", FormMethod.Post, new { id = "frmUpdate" }))
{
//have my form here
//use type button
}

Related

Asp.net core controller function with return partial view with select2 not working and remote function validation is not firing in modal popup

Select2 is not working and remote validation is not firing, this is only happens when I convert the code to modal popup but if not everything is working properly. What Am I missing in my code? Any advise or help much appreciated.. Thank you
Here is my code the modal:
$('#tbProducts tbody').on('click', 'button', function () {
var data = productsTable.row($(this).parents('tr')).data();
//alert(data.id);
$.ajax({
url: '#Url.Action("Edit", "Products")',
type: 'GET',
data: { id: data.id },
success: function (result) {
$('#EditUnitModal .modal-content').html(result);
$('#EditUnitModal').modal()
}
});
});
Here is the controller edit code:
public async Task<IActionResult> Edit(int? id)
{
//code here
return PartialView("__Edit", product);
}
And here is my partial view __Edit code:
#model intPOS.Models.Master.ViewModel.ProductViewModel
//code here
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$('#Unit').select2({
theme: 'bootstrap4',
dropdownParent: $('#EditUnitModal')
})
$('#Category').select2({
theme: 'bootstrap4',
dropdownParent: $('#EditUnitModal')
})
})
</script>
}
And View model code:
[Display(Name = "Product Code"), Required]
[Remote("CheckProduct", "Products", AdditionalFields = "Id", ErrorMessage = "Product already exists.")]
public string ProductCode
{
get
{
return _productcode;
}
set
{
_productcode = value.Trim();
}
}
Sample screen for not firing validation and select2 is not working:
sections aren't allowed in partial views. You can still use modals and partial views via Ajax for edit forms but there is a small modification you need to do in order for this to work:
Include all the necessary scripts in your page (this is mandatory as sections aren't allowed in partial views).
In your javascript code add these lines in order to parse the new form via jquery validation unobtrusive and your select elements via Select2.
$('#tbProducts tbody').on('click', 'button', function () {
var data = productsTable.row($(this).parents('tr')).data();
//alert(data.id);
$.ajax({
url: '#Url.Action("Edit", "Products")',
type: 'GET',
data: { id: data.id },
success: function (result) {
$('#EditUnitModal .modal-content').html(result);
//Here we parse the new form via jquery validation unobtrusive.
$.validator.unobtrusive.parse($('#EditUnitModal .modal-content form')[0]);
//Here we initialize select2 for the selected elements.
$(".yourSelect2ElementClass").select2({//options...});
//Now we launch the modal.
$('#EditUnitModal').modal()
}
});
});
Don't forget to remove the section from your partial view and include your scripts in the containing view.

Can't load data using Ajax for Razor Pages

I have this ajax call in my view, Form.cshtml
<form id="myForm">
<input id="btnSubmit" type="submit" value="Load data" />
<p id="result"></p>
</form>
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
debugger
$.get('/Form/',function (data) {
debugger
console.log('test');
});
})
});
</script>
}
and in my Razor Pages code behind, Form.cshtml.cs
public class FormModel : PageModel
{
public JsonResult OnPost()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The problem is it doesn't reach OnPost method. If I put in OnGet, it will automatically load before I click the Submit button.
I try to create another Razor page called Filter.cshtml and in Filter.cshtml.cs. And then in my Form.cshtml, I changed my url to /Filter/, it did reach OnGet in Filter.cshtml.cs
public class FilterModel : PageModel
{
public JsonResult OnGet()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The default behaviour of clicking a submit button in a form is that the form gets submitted. At the moment, your form has no method specified, so the submission will default to the GET method. If you want to submit the form by AJAX POST rather than the usual behaviour, you need to do two things:
Cancel the default action of the button click (which is what currently causes the OnGet handler to execute)
Change the jQuery code to use the POST method:
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function (e) { // include the event parameter
e.preventDefault(); // prevents the default submission of the form
$.post('/Form/',function (data) { // change from 'get' to 'post'
console.log('test');
});
});
});
</script>
}
the $.get() makes Ajax requests using the HTTP GET method, whereas the $.post() makes Ajax requests using the HTTP POST method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Filter/OnGet",
success: function (result) {
}
});

Ajax request off an MVC Form

I am trying to do an ajax request and depending on the ajax request results I will allow the form to submit to the controller. However everytime the ajax request runs I get the error message.
Here is my javascript function:
function CheckForValidation(e) {
var scholarshipRequest = $("#scholars").val();
var aidYearRequest = $("#aidYear").val();
var amountRequest = $("#amount").val();
$.ajax({
type: "POST",
url: '#Url.Action("Validate_ScholarshipRequest", "RequestController")',
data: {
scholarshipId: scholarshipRequest,
aidYear: aidYearRequest,
amount: amountRequest
}
}).success(function(response) {
if (!response.success) {
e.preventDefault();
alert(success);
} else {
e.preventDefault();
}
}).error(function() {
e.preventDefault();
alert("Error on Submission");
});
}
This function is called from here:
$("#SubmitTutorRequestFrm").submit(function(e) {
e.PreventDefault();
CheckForValidation(e);
});
I try to debug the code and put a breakpoint on Validate_ScholarshipRequest but that method never gets called. The method signature is:
public ActionResult Validate_ScholarshipRequest(string scholarshipId, string aidYear, string amount)
This is the start of my form:
#using (Html.BeginForm("SubmitScholarshipRequest", "Request", FormMethod.Post, new { id = "SubmitTutorRequestFrm" }))
Just to get this officially answered and "closed", this was caused by a syntax-error:
url: '#Url.Action("Validate_ScholarshipRequest", "RequestController")',
Controller should not be included in the controller name. The correct action would then be:
url: '#Url.Action("Validate_ScholarshipRequest", "Request")',

Submitting form with file using ajax and bootstrap modal

I am trying to submit some data and file to my controller's action:
[HttpPost]
public ActionResult Settle(SettlePrepaymentViewModel settlePrepaymentViewModel)
{
//Do something and return JSON
}
My view model contains the following properties:
public HttpPostedFileBase File { get; set; }
public Guid? PrepaymentId { get; set; }
In my form I have some textboxes and a file input. When I press button, I want my form (with file) to be submitted to my action:
$('#btnConfirmSettlement').click(function (e) {
$.ajax({
url: '#Url.Action("Settle", "Prepayments")',
type: "POST",
data: $("#uploadFile").serialize(),
success: function (data) {
if (data.isSuccess) {
toastr.success("Success");
} else {
toastr.error(data.errorMessage);
}
},
error: function (data) {
toastr.error(data.errorMessage);
}
});
return false;
});
However when using the above code it does not work (there is no file passed to my action. However when using the following code (where my form is simply submitted) it works fine:
#using (Html.BeginForm("Settle", "Prepayments", FormMethod.Post, new {enctype = "multipart/form-data", #id="uploadFileSubmi"}))
{
#Html.TextBoxFor(model => model.SettlePrepaymentViewModel.File, new {type = "file"})
<input type="submit" value="Settle"/>
}
I was trying to use form submit when I click "Save" on my twitter bootstrap modal but then it just returns me (redirects me to) a JSON result from my action - I don't want to be redirected. Can someone please help me with this? What am I doing wrong?

ASP MVC 3: Client Validation not working properly when submitting a form using AJAX

I have the following scenario, I have a for that I'm submitting using ajax using the following code:
$("#cmdAjaxSave").click(function (evt) {
evt.preventDefault();
var $form = $('#frmItem');
if ($form.valid()) {
ajaxSave();
}
});
function ajaxSave() {
if (!onBeforeSubmit()) return; //item is not valid, so the ajax call should not be executed
//var token = $('[name=__RequestVerificationToken]').val();
popup('ajaxSplash');
$.ajax({
type: "POST",
url: '#Url.Action("Index")',
data: $("#frmItem").serialize(),
success: function (html) {
//console.log(html);
$("#formDiv").empty();
$("#formDiv").append(html);
initItemPage();
alert("Item was saved successfully");
},
error: function () { popup('ajaxSplash'); onFailure(); }
});
}
The problem I'm seeing here is that even though "frmItem" is returning "true" when I arrive clientside the ModelState is not valid. Specifically for three properties, which actually has the correct value.
Digging into the code made by the developer who originally coded this I found that for instance this property:
#Html.TextBoxFor(model => model.Item.Service.CPC_BW, htmlAttributes: new { #class = "Text", #onkeyup = "validItem();", #id = "SrvCPCBlk" })
Is actually defined like this:
private double _CPC_BW;
[Required]
[Range(0, 100000, ErrorMessage = "CPC value required")]
public string CPC_BW { get { return String.Format("{0:F}", _CPC_BW); } set { _CPC_BW = Convert.ToDouble(value); } }
I think he did it because TextBoxFor does not offers an obvious way to format a number and even though it looks fishy I don't know how could this be causing the error.
The Html of the form is rendered like this
<div id="itemPopUpForm">
#{Html.EnableClientValidation();}
<div id="formDiv">
#{ Html.RenderPartial("ItemData", Model, new ViewDataDictionary() { { "Machines", ViewBag.Machines }, { "WarehouseList", ViewBag.WarehouseList }, { WebConstants.FORM_ID_KEY, #ViewData[WebConstants.FORM_ID_KEY] } }); }
</div>
</div>
The partial view contains the form that is submited in the ajax request.
I think you should try and clear the model state then test whether its valid...
Its a common issue.
ModelState.Clear();
ModelState.IsValid();

Resources