Customizing [Success] Messages in Asp.Net MVC - asp.net-mvc

I have found many articles about customizing error messages in asp.net mvc.
What I would like to know is how to show a success message.
For example, when I enter a valid email address I would show that the data entered has passed the validation by either changing the style of the control in which it was entered or providing a successful validation message.
All the asp.net mvc samples I have see so far explain how to display or customize error messages after failing validation.
I would like to know how to show a success message when the validation succeeds.
Does anyone know how to do this or know of a link/resource that can show me how?
Thanks in advance.

You can override the unobtrusive clientside validation setting in asp.net mvc3.
You can see how to do this here
The most important code in from the url is:
$(function() {
var settngs = $.data($('form')[0], 'validator').settings;
var oldErrorFunction = settngs.errorPlacement;
var oldSucessFunction = settngs.success;
settngs.errorPlacement = function (error, inputElement) {
//Do something here
oldErrorFunction(error, inputElement);
}
settngs.success = function (error) {
//Do something here
oldSucessFunction(error);
}
});

Its a good idea to show success message. You can display a success message by applying jquery on view's button click where you are submitting data.

Related

Symfony Form reset after submit

I have a very simple form created with createFormBuilder providing one simple text field only (there is no entity attached to the form).
When the form is submitted I do some logic and then unset form and formData as suggested in many posts to this topic if you want the form to be reset after submitting.
There is some additional action by simple ajax-requests that mainly initiates some UI stuff - not touching the form itself nor reloading the page.
Everything works fine except that the form apparently just doesn't want to be reset - meaning: Whenever the page reload button in the browser is pressed the standard browser dialog appears that asks if you want to submit the form again. And when you do the last value typed in BEFORE the last render call is submitted.
The template kw.html.twig is straight forward - mainly some UI stuff the form rendering and a bit jquery for handling ajax. Nothing special there.
I can't figure out why this is happening - I just want a clean form on any request. Which I thought I get when unsetting thing like in the sample code below.
/**
* #Route("/kw", name="show_kw")
*/
public function showKwAction(Request $request)
{
if($request->isXmlHttpRequest()) {
if( $request->getMethod() == 'POST' ) {
// do some logic...
return $this->json(array('kw_success' => true));
}
}
$kwData = array();
$kwForm = $this->createFormBuilder($kwData)
->add('kd', TextType::class)
->getForm();
if( $request->isMethod('POST') ) {
$kwForm->handleRequest($request);
$formData = $kwForm->getData();
// do some logic with formData...
unset($kwData);
unset($kwForm);
$kwData = array();
$kwForm = $this->createFormBuilder($kwData)
->add('kd', TextType::class)
->getForm();
}
$templateData = array(
'kwForm' => $kwForm->createView()
);
return $this->render(':backend:kw.html.twig', $templateData);
}
Any help is highly appreciated.
EDIT: Using Symfony 3.1
It's exactly what Alsatian said in the comment. Browser is trying to repeat last request.
However I think that instead of destroying this form you can simply redirect to the same route with $this->redirectToRoute once you processed data, of course if it's not a problem.
Also I see you check at least twice if method is post. If it's not colliding with the rest of your application logic you can specify #Method("POST") in annotation so you don't have to check it directly in code anymore.
Best Regards,
R.

ValidateInputAttribute not working in Post Request of ASP.NET MVC controller

My understanding was OOTB, MVC will validate input to prevent XSS Attack and SQL Injection.
For example, In one of my app, the "a dangerous input has been detected" error will be received when I put in HTTP Get request. However, the post actions can let these values posted successfully through html input element without error. Even after I marked the controller action as [ValidateInput(true)]. How can I make them validate those post input?
Any advice will be appreciated!
Without seeing your GET handler, or what you're sending to it, it's tough to say why it behaves that way. However, OOTB MVC guards against SQL injection through the use of Entity Framework, and against XSS through ModelState validation.
Inside the body of your POST action that handles this forms submission you'll want to use code much like the following:
if (ModelState.IsValid)
{
//do the stuff I want to do when things are valid and free of XSS
}
else
{
//something went wrong. Probably shouldn't process this one. Have the user try again
}
Update: please disregard my filthy lies. ValidateInput(true) is not necessary because it is on by default. So, the only things I can think of would be that you have the AllowHtml attribute on your class or properties, or you are not posting back a model for modelBinding, and therefore input validation, to occur. At this point, you're probably going to need to put up some code for further help. There's too many unknowns right now.
I ran into a similar issue - we had JQuery using $.ajax to post JSON to the MVC action. The default model binder does not validate posted JSON allowing unsafe XSS to be posted against our action.
To solve this, I found the RequestValidator has a static method InvokeIsValidRequestString that allowed
public class ValidateJsonXssAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext?.Request;
if (request != null && "application/json".Equals(request.ContentType, StringComparison.OrdinalIgnoreCase))
{
if (request.ContentLength > 0 && request.Form.Count == 0) //
{
if (request.InputStream.Position > 0)
request.InputStream.Position = 0; // InputStream has already been read once from "ProcessRequest"
using (var reader = new StreamReader(request.InputStream))
{
var postedContent = reader.ReadToEnd(); // Get posted JSON content
var isValid = RequestValidator.Current.InvokeIsValidRequestString(HttpContext.Current, postedContent,
RequestValidationSource.Form, "postedJson", out var failureIndex); // Invoke XSS validation
if (!isValid) // Not valid, so throw request validation exception
throw new HttpRequestValidationException("Potentially unsafe input detected");
}
}
}
}
}
Then, you can just decorate relevant MVC actions expecting JSON-posted data that might bypass the standard XSS prevention:
[HttpPost]
[ValidateJsonXss]
public ActionResult PublishRecord(RecordViewModel vm) { ... }
You can see other options for customizing request validation with OWASP .NET recommendations by extending the RequestValidator object, which exposes the string validation done by the ValidateInput automatically utilized by MVC for other scenarios of query string, form collection, and cookie values.
For more info: https://www.owasp.org/index.php/ASP.NET_Request_Validation

Textbox ENTER to save the text to DB -- MVC

I have a text box and if user types something and Hit enter it should save it to the DB.
#Html.TextArea("txtComments", new {#style = "width: 450px;",#placeholder = "Enter Comments here" })
Basically am looking for an event to fire on ENTER. and am implementing in RAZOR MVC.
i saw few ideas of keeping and other stuffs. But i thought this is the better place to post it.
Thanks
Basically am looking for an event to fire on ENTER
You could subscribe to the .keypress() event of the textarea and detect if Enter was pressed:
$(function() {
$('#txtComments').keypress(function() {
var code = e.keyCode ? e.keyCode : e.which;
if(code == 13) {
// Enter was pressed => act accordingly
}
});
});
and am implementing in RAZOR MVC.
Razor is a view engine which runs on the server. You cannot detect key presses on the server. You will have to use client side scripting (javascript) as I have shown previously.

validating email address using AJAX

Is there an easy way to check an email address is valid using Ajax? I'm using the sfValidatortEmail widget currently and this only shows an error message on submitting the form.
Thanks
I'm assuming you know how to write ajax requests. In the action you'd have something like
if ($request->isXmlHttpRequest()) {
// handle ajax check
try{
$validator = new sfValidatorEmail();
$validator->clean($request->getParameter('email'));
// good to go
} catch(sfValidatorError $e){
// invalid email
$this->getResponse()->setStatusCode(400);
}
} else {
// handle normal post
}
You'd need to add some Javascript/Jquery to fire an Ajax request to check the email, possibly linked to when the user clicks out of the email input box (blur function). This would be separate from your form class (assuming that the form has other elements too), but you could use the same action to handle the request if you wish:
if ($request->isXmlHttpRequest()) {
// handle ajax check
} else {
// handle normal post
}

Trying to join two independent forms

i'm trying to join two independent forms (login and register) in the
same page.
My idea is (just looking at the signin form):
Create an action that shows both forms (partials):
public function executeLoginAndRegister(sfWebRequest $request){
$this->form_signin = $this->getUser()->getAttribute('form_signin');
}
Each partial calls to its action:
form action="php?> echo url_for('#sf_guard_signin') ?>" method="post">
In the actions i write this code
public function executeSignin($request)
{
//...
$this->form = new $MyFormclass();
if ($this->form->isValid())
{
//...
}else{
// save the form to show the error messages.
$this->getUser()->setAttribute('form_signin', $this->form);
return $this->forward('sfGuardAuth', 'loginAndRegister');
}
}
It works, but, for example, if i execute LoginAndRegister and submit
incorrectly the signin form and I go to another page and then return to
LoginAndRegister, i will find the submiting error messages...
If i execute LoginAndRegister and submit incorrectly the signin form and
open another browser tab, i will find the submiting error messages in
the signin form of the second tab...
Any idea? any better approach?
I would just use sfDoctrineApplyPlugin if i were you :)
I have it, just writing in the if "request->isMethod('post')":
public function executeLoginAndRegister(sfWebRequest $request){
if($request->isMethod('post')){
$this->form_signin = $this->getUser()->getAttribute('form_signin');
}
}
Anyway if my approach has any big error or is not safety i would
thank anyone who tell me.
Javi

Resources