Flexabust Bergson Flexabust Bergson - 2 months ago 17
HTML Question

IsPost is not working correctly

I am posting a form and checking it's completion using

IsPost
but I never get the result I want :

@if (IsPost)
{
var error = false;
var nom = Request["searchGroup"];
if (nom.IsEmpty())
{
error = true;
@:Fill the form <br />
}
if (!error)
{
Response.Redirect(Href("~/Search/FindGroups"), false);
}
}

<form class="form-inline" method="post" action="~/Search/FindGroups">
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchGroup" id="searchGroup"/>
<button type="submit" id="searchValidate"> Rechercher </button><br />

</form>


So this is my form, when I post the form with an empty
<input>
it should show 'Fill the form' and not change page, but instead it redirects everytime. What am I not seeing?

Answer Source

it looks like you want to validate the textbox before form submission you can add id in from

<form class="form-inline" id="myform" method="post" action="~/Search/FindGroups">
    <input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchGroup" id="searchGroup"/>
    <button type="submit" id="searchValidate"> Rechercher </button><br />

</form>

and in jquery add this

$("#searchValidate").click(function(e){

e.preventDefault();
if($('#searchGroup').val() === "")
 {
   alert("Fill the form")
 }
else{
   $("#myform").submit();
 }
 });

and dont forget to add this in head

   <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="crossorigin="anonymous"></script>

and here is a working example https://jsfiddle.net/t04p54v4/