Unable to clear ModelState errors client side? Is it even possible? - javascript

Obviously I am using #Html.ValidationSummary() in my View to display any errors that may have occurred when the user posted to my controller.
However this is my scenario
The user posts to the controller and ModelState.IsValid = false;
#Html.ValidationSummary() displays my error message to the user.
Now the user corrects the error and clicks the submit button. However I want to clear that error message because I may present the user another option (client side script) prior to the post actually occurring.
I've tried various techniques for hiding the Validation Summary section to no avail.
function resetValidation() {
$("form").data("valmsg-summary").hide();
$(".field-validation-error").addClass("field-validation-valid");
$(".input-validation-error").addClass("input-validation-valid");
$(".validation-summary-errors").addClass("validation-summary-valid");
$(".field-validation-error").removeClass("field-validation-error");
$(".input-validation-error").removeClass("input-validation-error");
$(".validation-summary-errors").removeClass("validation-summary-errors");
};
This is the script of my Submit button.
$("#btnSubmit").click(function (e) {
resetValidation(); // Trying to suppress/clear error messages
var doPost = true;
var p1 = $("#Field1").val();
var p2 = $("#Field2").val();
var p3 = $("#Field3").val();
$.ajax({
type: "GET",
url: "/MyController/MyAction",
data: { "param1": p1, "param2": p2, "param3": p3 },
async: false
}).done(function (data) {
if (data > 999)
{
// I then display a new set of fields for the user to answer
doPost = false;
}
}).fail(function (xhr, status, err) {
alert(xhr.responseText);
});
return doPost;
});
Am I going about this the wrong way?Is it possible to clear the modelview errors client side?

Thanks to Stephen Muecke for the solution:
$(".validation-summary-errors").empty();

Related

ASP.NET MVC 500 (Internal Server Error) with ajax post method

I'm newbie in asp.net mvc, I try to create a post data using ajax, when in the development is run well, but when I try to publish web in server I get the error when post data, the error like this POST https://example.com/login-testing 500 (Internal Server Error). I try to look for many examples but fail all.
this is my code, may be you can find any problem in my code:
JS script in index.cshtml
function login() {
var email = $('#input-email').val();
var password = $('#input-password').val();
if (email && password) {
$.ajax({
url: '#Url.Action("LoginTesting", "Auth")',
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
dataType: 'json',
contentType: 'application/json',
success: function (data){
console.log(data);
if (data == 1) {
window.location.href = '#Url.Action("Index", "Home")';
} else {
$('#login-warning').show();
}
},
error: function (data) {
$('#login-warning').show();
}
});
} else if (!email) {
$('#text-danger-email').show();
} else if (!password) {
$('#text-danger-password').show();
}
}
controller
[Route("login-testing")]
public JsonResult LoginTesting(LoginViewModel smodel)
{
var email = smodel.email;
var password = smodel.password;
DBHandle sdb = new DBHandle();
var account = sdb.GetLoginVerify(email);
if (account.password != null)
{
if (BCrypt.Net.BCrypt.Verify(password, account.password ))
{
var detail = sdb.GetUserDetail(account.id);
if (detail != null)
{
Session["is_login"] = true;
Session["id"] = detail.id;
Session["fullname"] = detail.fullname;
Session["id_levels"] = detail.id_levels;
Session["levels"] = detail.levels;
return Json(1);
}
else
{
return Json(2);
}
}
else
{
return Json(3);
}
}
else
{
return Json(4);
}
}
Please anyone help me to solve this problem.
Thanks.
Internal Server Error probably means something is wrong with your program.cs file .The order in which they are placed is important,improper placements could actually give rise to these errors.
500 internal server also means , there is something wrong with your Code,
according to me Go to Chrome Dev Tool and Click on Network Tab, in that Click on XHR tab
there your API call must located with red Highlighted text (Since its 500 internal server error ), Click on it, right side window will be appear then
click on Preview Tab , you might see which line of Code causing the issue
You can also Debug the Code , and step over code line by line, and check what is wrong.

Inconsistent execution of Error function for Jquery Ajax POST request

I am running into an issue in my error handling of a Jquery Ajax request, and I'm having trouble finding the root of it.
I have a staging site where I am testing error responses for a form submission. The first time I fill out the form fully and click submit, the form is replaced with a brief "processing" message, and then input fields re-appear with the expected error message for Invalid Token.
However, when I click subsequent times sometimes it gets stuck on showing the "processing" message, even though I can see an Error response. It is strange because the console.error() that I have in my Error: function gets triggered, but the Jquery calls that should handle the Form's state don't seem to get complete even though they are in the same scope.
Here is are the jquery variables handling the form's state:
const $formErrorState = $('#SIM-Order-Error-State');
const $formErrorStateText = $('#SIM-Order-Error-State-Text');
const $formCompleteState = $('#SIM-order-complete-state');
const $formSuccessState = $('#SIM-order-success-state');
const $formInitialState = $('#SIM-order-form');
and the call itself:
function simOrderRequest(token, fData){
console.log(fData);
console.log(JSON.stringify(fData));
$.ajax({
method: 'POST',
url: 'https://control.dev.yomobile.xyz/api/v1.0/sim-request/confirm/?token='+token,
data: JSON.stringify(fData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.type=="bad_request" || data.status==400) {
$formErrorState.show();
$formSuccessState.hide();
$formErrorStateText.text(data.responseJSON.type+": "+data.responseJSON.description);
$formInitialState.show();
}
if (data.status==500){
$formErrorState.show();
$formSuccessState.hide();
$formErrorStateText.text(data.responseJSON.type+": "+data.responseJSON.description);
$formInitialState.show();
}else {
$formCompleteState.show();
$formSuccessState.hide();
}
},
error: function (error) {
$formSuccessState.hide();
$formErrorState.show();
$formInitialState.show();
$formErrorStateText.text(error.responseJSON.type+": "+error.responseJSON.description);
console.error(error);
},
});
}
});
This is the expected behavior
But sometimes it gets stuck here, once the error is returned, and does not return to the input fields

Call ActionMethod of a Controller in ASP.NET MVC from Javascript that results in Excel Worksheet saved

I would like to call an ActionMethod of a Controller that returns an Excel Worksheet.
I know that I could simply redirect the URL to http://website/Excel/GenerateReport
and it would work.
But I would like to popup a busy spinner right before the call to controller and close the spinner right after.
In the mean time the Controller's ActionMethod would generate Excel Report and return it.
The ActionMethod looks like this:
public ActionResult CreateReport()
{
try
{
// Opening the Excel template...
var fs = new FileStream(Server.MapPath(#"~\Content\Excel\Template.xlsx"), FileMode.Open, FileAccess.Read);
// Getting the complete workbook...
var templateWorkbook = new XSSFWorkbook(fs);
// Getting the worksheet by its name...
//HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");
var sheet = templateWorkbook.GetSheet("Report");
// Getting the row... 0 is the first row.
//HSSFRow dataRow = sheet.GetRow(4);
var dataRow = sheet.GetRow(4);
dataRow.CreateCell(0, CellType.Numeric);
dataRow.GetCell(0).SetCellValue(11.11);
// Forcing formula recalculation...
sheet.ForceFormulaRecalculation = true;
var ms = new MemoryStream();
// Writing the workbook content to the FileStream...
templateWorkbook.Write(ms);
TempData["Message"] = "Excel report created successfully!";
// Sending the server processed data back to the user computer...
return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");
}
catch (Exception ex)
{
TempData["Message"] = "Oops! Something went wrong.";
return RedirectToAction("NPOI");
}
}
I tried ajax but not luck...
Here's a general idea what I tried:
showProgress();
$.ajax({
url: ajaxUrl,
type: "get",
data: {
tmoCode: $("#tmoDropDownList").val(),
clientCode: $("#clientDropDownList").val(),
productCode: $("#productDropDownList").val(),
startDateCode: $("#startDateDropDownList").val(),
endDateCode: $("#endDateDropDownList").val()
},
success: function (response, textStatus, jqXHR) {
alert("Success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Creating Excel Report!");
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function () {
hideProgress();
}
});
Any idea is appreciated!
But please remember that I need to:
1. display the Spinner
2. run the report and return it as excel worksheet
3. hide the Spinner
Thanks in advance!
Check it out - https://github.com/johnculviner/jquery.fileDownload and see a demo - http://jqueryfiledownload.apphb.com/
You can use something like this:
$(function() {
$(document).on("click", "a.downloadFile", function() {
showProgress();
$.fileDownload($(this).prop('href'), {
successCallback: function(url) {
hideProgress();
},
failCallback: function(responseHtml, url) {
hideProgress();
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
});
});

Mutually exclusive submits

I have a javascript which on a "submit" event does the following ajax call(which in turn triggers a python script),my problem now is that "when one submit event is going on if anyone else clicks on
the submit button this ajax call should notify that a submission is in progress" ,has anyone ran into this problem?(is there a name?) ,how do fix this problem?
Please suggest..
$("#main_form").submit(function(event) {
.....................
$.ajax({
dataType: "json",
type: "POST",
contentType: "application/json",//note the contentType definition
url: "scripts/cherrypick.py",
data: JSON.stringify(data_cp),
//data: data_cp,
error : function (xhr, ajaxOptions, thrownError){
console.log("cherypick fail");
console.log(response);
console.log(response['returnArray']);
alert(xhr.status);
alert(thrownError);
},
success: function(response){
console.log("cherypick sucess");
console.log(response);
console.log(response['returnArray']);
var return_array = response['returnArray'];
console.log(return_array['faillist'].length);
console.log(return_array['picklist'].length);
for (var i = 0; i < ip_gerrits.length; ) {
for (var j = 0; j < return_array['faillist'].length; ) {
if (ip_gerrits[i] != return_array['faillist'][j] )
ipgerrits_pickuplist.push(ip_gerrits[i]);
j++;
}
i++;
}
Ok, as far as you want to synchronize requests processing for all users, it should be done on the server side. I assume that your server side is Python, even though you did not add relevant tag to your question. My preferences are C# and PHP, but in your case I would do the following ...
Options # 1 - Session
1) add or install preferable session module for Python, crowd recommends to use Beaker
Python Module for Session Management
2) send AJAX request to the server side script
$(form).submit(function(e) {
var options = {
url: "scripts/cherrypick.py"
};
$.ajax(options);
});
3) this server side script will have something like this code
session_opts = {
'session.type': 'file',
'session.data_dir': './session/',
'session.auto': True,
}
app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
#hook('before_request')
def setup_request():
request.session = request.environ['beaker.session']
#route('/cherrypick')
def index():
if 'processing' in request.session:
data = { 'procesing': request.session['processing'] }
return data
processor()
def processor():
request.session['processing'] = 1
# Do some processing here for the first request
# When processing is done you can clear "state" variable in session
del request.session['processing']
request.session.modified = True
Bottle.py session with Beaker
http://beaker.readthedocs.org/en/latest/sessions.html#using
http://flask.pocoo.org/snippets/61/
4) Now in your JS script if you get JSON that contains key "processing" you may show alert to the user that he needs to wait until first request is processed
Option # 2 - Long Polling and Comet
Description of this option may take much more space to describe, thus it is better to look at this article, it has quite nice and clean example and implementation of long polling in Python
http://blog.oddbit.com/2013/11/23/long-polling-with-ja/
The main idea here is not to keep static session but use infinite loop instead that can send back different HTTP responses depending on some state variable :
#route('/cherrypick')
def index():
while True :
response = { 'processing': processing }
print response
if processing != 1 :
processing = 1
# Do some processing
processing = 0
sleep(5)
The simplest way is to close around a flag that indicates some processing is underway:
var processing = false;
$("#main_form").submit(function(event) {
if (processing) {
$("#some_notification_pane").text("hold on there, turbo!");
return;
}
processing = true;
...
$.ajax({
...
error: function(xhr, ajaxOptions, thrownError) {
...
processing = false;
},
success: function(response) {
...
processing = false;
}
});
...
});
You might also want to disable the submit button at the beginning of the submit handler (where I have processing = true) and re-enable it after receiving a response.

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

Categories