button cannot trigger in mvc 4 - asp.net-mvc

I am having some trouble in ASP.NET MVC4 - When I click the Login button it's not hitting my controller and not logging in
This is the code on my .cshtml
#using System.Linq
<body>
<div class="container">
#using (Html.BeginForm("Login", "Login", FormMethod.Post, new { #Class = "form-signin", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "Login failed. Check your login details.")
<img class="img-responsive" src="~/Images/PI%20Logo.jpg" />
#Html.TextBoxFor(m => m.userName, new {#Class = "form-control", #Id = "user", #placeholder = "Username"})
#Html.ValidationMessageFor(m => m.userName)
#Html.PasswordFor(p => p.passwd, new {#Class = "form-control", #Id = "pass", #placeholder = "Password"})
#Html.ValidationMessageFor(m => m.passwd)
<!--<input class="form-control" id="username" placeholder="Username" type="text" />
<input class="form-control" id="Password1" placeholder="Password" type="password" /> -->
<input id="submit" class="btn btn-lg btn-primary btn-block" type="button" value="LOGIN" />
}
</div>
<script src="~/Scripts/jquery-1.11.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</body>
and this is my controller
public class LoginController : Controller
{
//
// GET: /Login/
public ActionResult Login()
{
return View();
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Login(Login login)
{
AccountManagement am = new AccountManagement();
var xrm = new XrmServiceContext("Xrm");
SystemUser sysUser = xrm.SystemUserSet.Where(x => x.DomainName == "hc\\" + login.userName && x.IsDisabled == false).FirstOrDefault();
if (am.ValidateCredentials(login.userName, login.passwd) == "True" && sysUser != null)
{
Session["username"] = login.userName;
return RedirectToAction("MainHome", "MainMenu");//Request.CreateResponse(HttpStatusCode.OK, new { Message = "Success", User = sysUser });
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");//Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Username or Password Invalid");
}
return View(login);
}
}
What's wrong with my code - i'm so confused, because many tutorial made simple login like this but it's work

Change button type to submit
<input id="submit" class="btn btn-lg btn-primary btn-block" type="submit" value="LOGIN" />
Difference between input type Button & submit
<input type="button" />
buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.
<input type="submit">
buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.

Related

Multiple forms in one view page

I'm working on an application that handles employee's profile.
I have 3 forms (all in the same controller) in a single view page, but it only saves the 1st form. And when i save the 2nd form, it clears the values of the 1st and 3rd form.
Here is my code:
Views/EMPs/Index:
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="personalsubmit" class="btn btn-success" />
</div>
</div>
}
#{ Html.RenderAction("Index", "EMP_REFERENCE", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="jobsubmit" class="btn btn-success" />
</div>
</div>
}
#{ Html.RenderAction("Index", "EMP_BENEFITS", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="otherssubmit" class="btn btn-success" />
</div>
</div>
}
EMPsController
public ActionResult Edit([Bind(Include = "lineno,EMPNO,IDNO..")] EMP eMP)
{
if (ModelState.IsValid)
{
if (Request.Form["personalsubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
if (Request.Form["jobsubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
if (Request.Form["otherssubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
return Redirect(Request.UrlReferrer.PathAndQuery);
}
return View(eMP);
}
I couldn't put them all in one form, because i used an ajax beginForm between them for another crud method. Since I've read that nested forms are not recommended.
Is there a way to save one form without it clearing the values of the other forms?
Is there a way to save one form without it clearing the values of the other forms?
You could simply use ajax.beginform for each of those forms;
How to use Simple Ajax Beginform in Asp.net MVC 4?
Or you could make your own ajax implementation
https://www.c-sharpcorner.com/blogs/using-ajax-in-asp-net-mvc
Or you could just go ahead and bind everything on your model;
// don't need to specify which properties to bind, all of the available properties in your view will be bound to the model on POST
public ActionResult Edit(EMP eMP)
{
if(eMP.FirstName!=null ...){
// ... do some checking depending on what values are submitted
}
// save profile here
// when you return the view
return View(eMP);
}
but for this method you need to only have 1 form for Personal,Job, and Others.
#{ Html.RenderAction("Index", "EMP_REFERENCE", new { id = Model.eMP.lineno });}
#{ Html.RenderAction("Index", "EMP_BENEFITS", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!--put all your employee input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
<!--put all your job input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
<!--put all your others input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
}

How to validate a duplicate post request from a form in MVC

I am having an form which insert a record whenever a post request is made,but the problem is that if someone clicks submit button more than 1 times than duplicate post request are made and at the end same records are getting inserted. I dont want to check that the record is already present or not because the record would be different always. I tried using ValidateAntiForgeryToken filter in controller but it is failing to validate the requests, Below is my View Code.
#using (Html.BeginForm("Create", "Home",FormMethod.Post,new { onkeydown = "return event.keyCode!=13" }))
{
#Html.AntiForgeryToken()
<div class="right-col">
#Html.TextBoxFor(model => model.Name, new { placeholder = "Name", #class = "small-box" })
</div>
<div class="left-col">Email Id :</div>
<div class="right-col">
#Html.TextBoxFor(model => model.EmailId, new { placeholder = "Email Id", #class = "small-box",id="resumeemailid" })
#Html.ValidationMessageFor(model => model.EmailId)
</div>
<div class="left-col">Address :</div>
<div class="right-col">
#Html.TextAreaFor(model => model.Address, new { placeholder = "Address", #class = "small-box" })
</div>
<div class="buttons resume-threebutton">
<input type="submit" id="register-button" class="gradient-btn" value="#T("Account.Passport.Register.Button.Upload", "Upload")" name="Command" />
<input type="submit" id="register-button" class="gradient-btn" value="#T("Account.Passport.Button.UploadandAdd", "Upload And Add New")" name="Command" />
<input type="button" id="register-button" class="gradient-btn" value="#T("Account.Passport.Register.Button.Cancel", "cancel")" name="register-button" onclick="location.href='#Url.Action("SelectTemplate", "CustomerTemplate")'" />
</div>
}
and below is my controller Post method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProductModel model)
{
//To do add the product here...
}

Prevent Modal Closing on form submit in Mvc

Is there a way to prevent the modal from closing when a form is submitted?
I am working on Email Sending Modal But When Click On Submit Button Controller Returns View, How To Prevent This ?
Modal Code Here:
#using (#Html.BeginForm("SendEmail", "Home", FormMethod.Post, new { #id = "form1", #enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<span class="btn green fileinput-button">
<i class="fa fa-plus fa fa-white"></i>
<span >Attachment</span>
<input type="file" multiple="multiple" name="files" id="file">
</span>
<button class="btn btn-send" type="submit" >Send</button>
#ViewBag.Message
<br />
</div>
</div>
}
Here is Email Controller Code:
public ActionResult SendEmail(EmailContent emailContent, List<HttpPostedFileBase> files)
{
ViewBag.Message = "Email Sent Successfully!";
return RedirectToAction("Index","Home");
}
catch
{
ViewBag.Project = new SelectList(db.employees, "employee_id", "name");
ViewBag.Message = "Failed to Send Email, Please Try Again";
return RedirectToAction("Index","Home");
}
}
}
Please Help i want return no view , modal still open.

How to load the page in a specific section in ASP.NET MVC

I am developing an ASP.NET MVC 5 web application using SQL Server with stored procedures.
In a defined case, I am trying to redirect the user in to a specific section of the page and not the top of page but I didn't succeed.
This is what I've tried :
Controller :
else
{
TempData["msg2"] = " Please verify your data !";
return RedirectToAction("Index" + "/" + "#login", "Home");
}
The view : (Index)
<div class="login" id="login">
<div class="main-w3l">
<div class="w3layouts-main" style="background-image:url('/template/web/images/bg3.jpg'); margin-top:50px;">
<h2>Login Now</h2>
#using (Html.BeginForm("Login", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<input value="E-MAIL" name="Email" type="email" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'E-Mail';}" />
<input value="PASSWORD" name="Password" type="password" required="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'password';}" />
<span><input type="checkbox" />Remember Me</span>
}
The URL that I get is here :
http://localhost:60585/(S(mnraq5fizd2wkqbg5pjpr5qu))/Home/Index/%23login#2249506

Ajax BeginForm POST using MVC and Razor

I keep getting a 404 and searching all over SO and cannot target the issue here. The form is the result of a render action and appears on the home page (home controller). However, I want it to post a different controller action and it keeps giving me a 404. I have included all the correct script for unobtrusive javascript as well as the necessary web.config settings and I'm unable to come across a similar problem from my research.
This is the partial with the form that is being rendered:
#model AFS.Models.SearchLocationModel
<div class="site-search-module">
<div class="site-search-module-inside">
#using (Ajax.BeginForm("SearchCare", "LevelOfCare", null, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchDiv" }, new { #class = "search-form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="row">
<div class="col-md-12">
<h5>Select a category</h5>
#Html.DropDownListFor(x => x.Level, Model.LevelSelectList, new { #class = "form-control input-lg selectpicker" })
</div>
<div class="col-md-12">
<h5>Enter location</h5>
<input type="text" id="Location" name="Location" class="form-control input-lg selectpicker" placeholder="City, State OR Zip Code" required />
</div>
<div class="col-md-12"> <button type="submit" class="btn btn-primary btn-block btn-lg search"><i class="fa fa-search"></i> Search</button> </div>
</div>
}
</div>
The controller action is:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SearchCare(SearchLocationModel model)
{
if (ModelState.IsValid)
{
SearchLocationModel geocodeModel = Geocode(new SearchLocationModel() { Level = model.Level, Location = model.Location });
if (geocodeModel.Status == "OK")
{
Session["level"] = model.Level;
return RedirectToRoute("LevelCity", new { level = model.Level, state = geocodeModel.State, city = geocodeModel.City, latitude = geocodeModel.Latitude, longitude = geocodeModel.Longitude });
}
else
{
ModelState.AddModelError(string.Empty, "Please enter City, State OR Zip Code.");
return RedirectToAction("SearchWidget", "Home");
}
}
else
{
return RedirectToAction("SearchError");
}
}

Resources