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.
Related
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>
}
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");
}
}
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.
I want to do a simple file upload using Html forms. I have the following in my view:
<form action='#Url.Action("Save", "Order")' method="post" enctype="multipart/form-data" id="attachmentForm">
<div >
<label style="text-align: left;">Delivery note:</label>
</div>
<div style="float:left; ">
<input type="file" name="DeliveryNoteFile" id="DeliveryNote" style="width: 400px;" />
</div>
<div style="float:right; margin-top:10px; margin-left:5px; margin-bottom:0px;">
#(Html.Kendo().Button()
.Name("btnAddAttachment")
.HtmlAttributes( new {type = "submit"} )
.Content("Submit"))
</div>
</form>
Now here is my controller method. Controller name: Order , Method name: Save.
Why is it not hitting my controller method?
[HttpPost]
public ActionResult Save(HttpPostedFileBase file)
{
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var physicalPath = Path.Combine(Server.MapPath("C:\\Attachments"), fileName);
file.SaveAs(physicalPath);
}
return Content("");
}
Note that this is only a first draft. Any suggestions to improve this are also welcome.
I think in your case your button is not of type submit that is why it is not hitting controller action just try making submit button this way:
#(Html.Kendo().Button()
.Name("btnAddAttachment")
.HtmlAttributes( new {type = "submit"} )
.Content("Submit"))
as # AbbasGaliyakot comment worked for the user in comment section so i m also including it here.
Change controller action parameter name from file to DeliveryNoteFile.
Please try this out. This would help.
#using (Html.BeginForm("Save", "Order", FormMethod.Post, new { enctype = "multipart/form-data", id = "attachmentForm" }))
{
<div >
<label style="text-align: left;">Delivery note:</label>
</div>
<div style="float:left; ">
<input type="file" name="DeliveryNoteFile" id="DeliveryNote" style="width: 400px;" />
</div>
<div style="float:right; margin-top:10px; margin-left:5px; margin-bottom:0px;">
#(Html.Kendo().Button()
.Name("btnAddAttachment")
.HtmlAttributes( new {type = "submit"} )
.Content("Submit"))
</div>
}
And in JS you need to bind the click function of your submit button like shown below:
$('#btnAddAttachment').bind('click', function () {
$('#attachmentForm').submit();
});
Thanks!
in the page I have only three checkbox, the client should choose at least one before clicking on the submit button :
Controller :
[HttpPost]
public ActionResult Client(OrderItems model)
{
if (bValidated){
//Code here
}
else
{
model.itemChoosed = false;
return View("Client", model);
}
View Client :
#model WebApp.Models.OrderItems
#using (Html.BeginForm("Client", "Home", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
#Html.AntiForgeryToken();
<h2>Client</h2>
#Html.Partial("SentMessage")
<div>
<div>
<h3>Item 1</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item1) Item 1</label>
</div>
<div>
<h3>Item 2</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item2) Item 2</label>
</div>
<div>
<h3>Item 3</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item3) Item 3</label>
</div>
</div>
<div class="row">
<input type="submit" name="action:Client" id="btnClient" class="btn btn-primary flat btn-large pull-right" value="Client" />
</div>
}
After I choose to put the condition into a Partail View :
Partial View SentMessage:
#model WebApp.Models.OrderItems
#if (!model.itemChoosed)
{
<div>You must choose at least one item</div>
}
I have the error message :
The view 'Client' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Client.aspx
..
~/Views/Home/Client.cshtml
..
but Home/Client.cshtml existe since it's the view
Thanks