i want to set the DDL selected item with item inserted in popup page.
Used script sample from here - http://www.advancesharp.com/blog/1126/search-sort-paging-insert-update-and-delete-with-asp-net-mvc-and-bootstrap-modal-popup-part-2
in JsonResult i see the inserted value (checking in Debug mode with breakpoint), but need help with setting this value as selected in DDL in main page.
public ActionResult WorkPlaces(int id = 0)
{
var workPlace = new Work();
return PartialView("WorkPlaces", workPlace);
}
[HttpPost]
public JsonResult WorkPlaces(Work work)
{
if (ModelState.IsValid)
{
db.Works.Add(work);
db.SaveChanges();
return Json(new { success = true });
}
return Json(work, JsonRequestBehavior.AllowGet);
}
Model classes
public class Person
{
public int Id { get; set; }
[Display(Name = "Person Name")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Name is required")]
public string Name { get; set; }
public Nullable<int> WorkId { get; set; }
public virtual Work Work { get; set; }
}
public class Work
{
public int Id { get; set; }
[Display(Name = "Work place")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Name is required")]
public string workPlace { get; set; }
}
Main page
#model testAppAuth.Models.Person
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Person</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WorkId, "WorkId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("WorkId", null, htmlAttributes: new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.WorkId, "", new {#class = "text-danger"})
<a class="btn btn-success" data-modal="" href="/Person/WorkPlaces" id="btnCreate">
<span class="glyphicon glyphicon-plus"></span>
</a>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
#section scripts{
#Scripts.Render("~/Scripts/Appjs/WorkPlace.js")
}
popup page
#model testAppAuth.Models.Work
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Add new workplace</h3>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Work place</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.workPlace, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.workPlace, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.workPlace, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="modal-footer">
<span id="progress" class="text-center" style="display: none;">
<img src="/images/wait.gif" alt="wiat" />
Wait..
</span>
<input class="btn btn-primary" type="submit" value="Save" />
<button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
}
<script>
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</script>
script for popup
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
location.reload();
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
Also, with this script even i set [Required] attribute in Model classes, it closes if i click close button without filling fields. How to make it not to close?
Your first question:
You can do this using Jquery:
When you are closing the dialog(Sucess) make a Jquery call to a function that will take the submitted value and change the selected item in your main page.
ex:
success: function (result) {
//change the selected item
}
Your second question:
The Ajax Call doesn't care about the Model Validation.
When you are submitting the data from your modal, validate the values of the required fields before making the AJAX Call.
ex.
$('form', dialog).submit(function () {
if(isValidInput()){
$('#progress').show();
//make Ajax Call
}
});
function IsValidInput(){
//do validation
}
For your Question how to validate before closing the Model use the below code
$(function () {
$('#myModal').on('hide.bs.modal', function (event) {
var form = $("#formid");
form.Validate();
if(form.Valid()){
//Ajax;
}
else{
event.PreventDefault();
}})});
Now in ajax Success used jquery to add value to DropDown
Related
I have the following View code in which I am displaying a list of flights.
#using Airline_Reservation_System.Models;
#{
AirlineContext ac = new AirlineContext();
var ddlcabin = ac.Cabins.ToList();
}
<div class="container d-flex flex-column align-items-center py-5">
#{
foreach (var item in Model)
{
<div class="flight mb-2">
<div class="info-label">
<span>Flight Info</span>
</div>
<div class="toFrom">
<h3 id="FCity_#item.FlightID">#item.FromCity </h3>
<span><i class="fa mx-4 fa-plane"></i></span>
<h3 id="TCity_#item.FlightID">#item.ToCity</h3>
</div>
<div class="info d-flex">
<p class="me-2 " id="DDate_#item.FlightID">#item.DepartureDate.ToShortDateString()</p>
<p class="me-2" id="DTime_#item.FlightID">#item.DepartureTime.ToShortTimeString()</p>
<p class="me-2 " id="ATime_#item.FlightID">#item.ArrivalTime.ToShortTimeString()</p>
<select id="CFare_#item.Fare" class="form-control me-2">
#foreach (var re in ddlcabin)
{
<option value="#re.CabinsId">#re.CabinName (#re.Fare)</option>
}
</select>
<button class="form-control btn btn-primary" onclick="Save(#item.FlightID,#item.CabinsId)">select </button>
#*#Html.ActionLink("Select", "ReserveFlight", "Flights", new { #class = "btn SelectFlight btn-primary" })*#
</div>
</div>
}
}
}
<script>
function Save(id, cabinsId) {
var Fid = id;
var cid = cabinsId;
window.location.href = '#Url.Action("signUp","User")';
$.ajax({
method: 'GET',
url:'/Flights/ReserveFlight',
data: { FlightId: Fid, CabinId: cid }
});
}
</script>
Here in the script section, I called the first action method signUp in the User controller and after that, in the Ajax call, I posted data on the URL /Flights/ReserveFlight
but the problem is that In the first call the control goes to the signUp method in the User controller, but before opening its view the control automatically goes to action called by ajax means to this action which is:
public ActionResult ReserveFlight(int FlightId, int CabinId)
{
FlightReservation reserve = new FlightReservation();
reserve.CabinsId = CabinId;
reserve.Id = FlightId;
reserve.PessengerId = Convert.ToInt32(Session["UserId"]);
db.FlightReservations.Add(reserve);
db.SaveChanges();
return View();
}
this action gets executed and on the line:
db.SaveChanges();
it shows an exception because the pessengerId is going null.
when I continue it then the view of the signUp method gets displayed.
here is the view:
#using (Html.BeginForm("signUp", "User", FormMethod.Post,))
{
<div>
<div>
<div>
#Html.EditorFor(model => model.FullName, new { htmlAttributes = new { #class = "form-control", id = "fullName" } })
</div>
</div>
<div>
<div class="col-md-5 offset-md-1">
#Html.DropDownListFor(m => m.Genderid, ViewBag.gender as SelectList, "--select gender--", htmlAttributes: new { #class = "form-control", id = "gender" })
</div>
<div class="col-md-5">
#Html.EditorFor(m => m.DOB, new { htmlAttributes = new { #class = "form-control", type = "date", id = "dob" } })
</div>
</div>
<div class="row mb-3">
<div class="col-md-5 offset-md-1">
#Html.EditorFor(model => model.contact, new { htmlAttributes = new { #class = "form-control", type = "number", id = "contact" } })
</div>
<div class="col-md-5">
#Html.EditorFor(model => model.Cnic, new { htmlAttributes = new { #class = "form-control", id = "cnic" } })
</div>
</div>
<div class="row mb-3">
<div class="col-md-10 offset-md-1">
#Html.DropDownListFor(m => m.CityId, ViewBag.cityList as SelectList, "--select city--", htmlAttributes: new { #class = "form-control", id = "city" })
</div>
</div>
<div class="row mb-3">
<div class="col-md-10 offset-md-1">
#Html.EditorFor(model => model.email, new { htmlAttributes = new { #class = "form-control", id = "email" } })
</div>
</div>
<div class="row mb-3">
<div class="col-md-5 offset-md-1">
#Html.EditorFor(model => model.password, new { htmlAttributes = new { #class = "form-control", id = "password" } })
</div>
<div class="col-md-5">
#Html.EditorFor(model => model.cPassword, new { htmlAttributes = new { #class = "form-control", id = "cpassword" } })
</div>
</div>
<div class="row">
<div class="offset-md-1 col-md-10">
<input type="button" value="Sign Up" class="btn btn-primary" onclick="signUp()" />
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-3.6.0.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
function signUp() {
var obj = {
FullName: $('#fullName').val(),
Genderid: $('#gender').val(),
DOB: $('#dob').val(),
Cnic: $('#cnic').val(),
CityId: $('#city').val(),
contact: $('#contact').val(),
email: $('#email').val(),
password: $('#password').val(),
cPassword: $('#cpassword').val()
};
$.ajax({
method: "POST",
url: "/User/signUp",
data: obj,
success: function () {
alert("success");
},
error: function () {
alert("failed");
}
});
}
</script>
when I submit the form, Data gets inserted into the database but In the ajax call section, the error callback function is executed and alert shows
failed
Im trying to call the java script confirmation form submit but it skips it. It directly calls the controller even though i want to run first the java script for confirmation.
I dont know what im doing wrong. Still new to JV Scripts.
HTML
#model WMS_Web.Models.FileMaintenance.PrincipalModels
#section Scripts {
#Scripts.Render("~/Script/FileMaintenance/CommonFunction.js")
}
#{
ViewBag.Title = "PrincipalModel";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Principal</h2>
#using (Html.BeginForm("Create","Principal",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CompanyId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CompanyId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CompanyId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button onclick='functionConfirm("Do you like Football?", function yes() {
alert("Yes")
},
function no() {
alert("no")
});'>XXX</button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back", "ViewPrincipal")
</div>
Java Script
function functionConfirm(msg, myYes, myNo) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.find(".no").click(myNo);
confirmBox.show();
}
You can try this:
#using (Html.BeginForm("Create","Principal",FormMethod.Post))
{
#Html.AntiForgeryToken()
...
<input type="submit" name="name" value="Save" onclick="javascript: return SubmitForm();" />
}
Javascript:
function SubmitForm() {
var r = confirm("Are you sure you want to submit?");
if (r == false) {
return false;
}
// do something
return true;
}
In my project, I have a main page for the document creation in DocumentsController where the user is able to change the status of the document. If the status is NEW, the user is allowed to add a new device ("part") to the document.
My goal is to insert a string to div#newDevice on ajax form submit. However, the html result is not rendered inside my main view but is rendered as a link ..../PartsBoxes/CreatePartial instead.
How could I fix that issue?
My main page part:
<input type="button" value="Add a new box" id="addNewBoxButton" class="add_new_btn" />
<input type="button" value="Add box from db" id="addDBBoxButton" class="add_existent_btn" />
<hr />
<div id="newDevice"></div>
<hr />
<script>
$("#addNewBoxButton").on("click", function () {
var deviceId = 1;
$.get('#Url.Action("CreatePartial", "PartsBoxes")',{
deviceId: deviceId
},
function (data) {
$("#newDevice").html(data);
});
});
</script>
my partial view:
#model NTStock.Models.BoxPartsViewModel
#{
ViewBag.Title = "Create";
}
#using (Ajax.BeginForm("CreatePartial", new AjaxOptions { UpdateTargetId = "newDevice" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.DocumentId)
<div class="form-group">
#Html.LabelFor(model => model.InternalName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.InternalName, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.InternalName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SerialNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SerialNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SerialNumber, "", new { #class = "text-danger" })
</div>
</div>
//......///
<div class="form-group deviceManipulations">
#Html.LabelFor(model => model.DeinstallationDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DeinstallationDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DeinstallationDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save box" class="btn btn-default" />
</div>
</div>
</div>
}
and the method:
[HttpPost]
[ValidateAntiForgeryToken]
public ContentResult CreatePartial(BoxPartsViewModel partsBox)
{
if (ModelState.IsValid)
{
//do something
}
return Content("string to return");
}
as a result I get:
Firstly you should be sure jquery.unobtrusive-ajax is loaded in your page and you dont use jquery 1.9 version because it doesnt support jquery live methods.
Reference : http://jquery.com/upgrade-guide/1.9/
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then I would suggest to use jquery .load() function to load partial view into target element and use JsonResult instead of ActionResult to achieve your goal like following.
// jquery
<script>
$("#addNewBoxButton").on("click", function () {
var deviceId = 1;
$("#newDevice").load('#Url.Action("CreatePartial", "PartsBoxes")' + "/" deviceId );
});
</script>
//controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult CreatePartial(BoxPartsViewModel partsBox)
{
if (ModelState.IsValid)
{
//do something
}
return Json(new { data = "string to return" });
}
MVC5 asp.net After validation the dialog form is break down
1. _Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - Moving Pro Services</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
#if (HttpContext.Current.User.Identity.IsAuthenticated)
{
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Moving Pro Services", "Index", "Home", new {area = ""}, new {#class = "navbar-brand"})
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
Services <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>#Html.ActionLink("Companies", "Index", "Companies")</li>
<li>#Html.ActionLink("App Versions", "Index", "AppVersions")</li>
#if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Administrator"))
{
<li>#Html.ActionLink("Create User", "Register", "Account")</li>
}
}
</ul>
</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
}
</div>
<div class="container body-content">
#RenderBody()
<hr/>
<footer>
<p>© #DateTime.Now.Year - Moving Pro Services</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
</body>
</html>
2. Model
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Maintenance.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Company
{
public int ID { get; set; }
[Display(Name = "Company Name")]
[StringLength(100)]
public string CompanyName { get; set; }
[Display(Name = "Server Alias")]
[StringLength(100)]
public string ServerAlias { get; set; }
[Display(Name = "Server Name")]
public string ServerName { get; set; }
[Display(Name = "Database Name")]
public string DatabaseName { get; set; }
[Display(Name = "Email Database Name")]
public string EmailDatabaseName { get; set; }
[Display(Name = "Integrated Security")]
public bool IntegratedSecurity { get; set; }
[Display(Name = "User Name")]
public string UserName { get; set; }
[Display(Name = "PWD")]
public string Password { get; set; }
[Display(Name = "App Key")]
public string AppKey { get; set; }
[StringLength(20)]
[Display(Name = "App Version")]
public string AppVersion { get; set; }
[Display(Name = "In Home Estimate")]
public bool InHomeEstimate { get; set; }
[Display(Name = "Foreman Inventory")]
public bool ForemanInventory { get; set; }
[Display(Name = "Docs")]
public bool Documents { get; set; }
[Display(Name = "Storage Scan In")]
public bool StorageScanIn { get; set; }
[Display(Name = "Storage Scan Out")]
public bool StorageScanOut { get; set; }
[Display(Name = "Scan At Delivery")]
public bool ScanAtDelivery { get; set; }
[Display(Name = "Amazon Rds")]
public bool AmazonRds { get; set; }
[Display(Name = "Amazon Region")]
[StringLength(20)]
public string AmazonRegion { get; set; }
[Display(Name = "Amazon Identifier")]
public string AmazonIdentifier { get; set; }
[Display(Name = "App Version")]
public virtual AppVersion AppVersion1 { get; set; }
}
}
3. Controller
// GET: Companies/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company company = _db.Companies.Find(id);
if (company == null)
{
return HttpNotFound();
}
ViewBag.AppVersion = new SelectList(_db.AppVersions, "AppVersion1", "AppVersionDescription", company.AppVersion);
return PartialView(company);
}
// POST: Companies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,CompanyName,ServerAlias,ServerName,DatabaseName,EmailDatabaseName,IntegratedSecurity,AppKey,AppVersion,InHomeEstimate,ForemanInventory,Documents,StorageScanIn,StorageScanOut,ScanAtDelivery,AmazonRds,AmazonRegion,AmazonIdentifier")] Company company)
{
if (ModelState.IsValid)
{
_db.Entry(company).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AppVersion = new SelectList(_db.AppVersions, "AppVersion1", "AppVersionDescription", company.AppVersion);
return PartialView(company);
}
4. View
#model Maintenance.Models.Company
#using (Html.BeginForm())
{
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Company</h4>
</div>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group margin-small">
#Html.LabelFor(model => model.CompanyName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { #class = "form-control", autofocus = "" } } )
#Html.ValidationMessageFor(model => model.CompanyName, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.ServerAlias, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.ServerAlias, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ServerAlias, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.ServerName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.ServerName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ServerName, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.DatabaseName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.DatabaseName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DatabaseName, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.EmailDatabaseName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.EmailDatabaseName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailDatabaseName, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.IntegratedSecurity, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.IntegratedSecurity, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.IntegratedSecurity, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.AppKey, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.AppKey, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AppKey, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.AppVersion, "App Version", htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.DropDownList("AppVersion", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AppVersion, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.InHomeEstimate, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.InHomeEstimate, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.InHomeEstimate, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.ForemanInventory, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.ForemanInventory, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.ForemanInventory, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.Documents, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.Documents, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.Documents, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.StorageScanIn, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.StorageScanIn, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.StorageScanIn, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.StorageScanOut, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.StorageScanOut, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.StorageScanOut, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.ScanAtDelivery, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.ScanAtDelivery, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.ScanAtDelivery, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.AmazonRds, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.AmazonRds, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.AmazonRds, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.AmazonRegion, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.AmazonRegion, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AmazonRegion, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.AmazonIdentifier, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.AmazonIdentifier, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AmazonIdentifier, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save changes" id="approve-btn" />
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
$(function () {
$("form input").tooltipValidation({
placement: "right"
});
});
</script>
}
Script to show dialog
$(function () {
$.ajaxSetup({ cache: false });
$(document).on("click", ".modal-link", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal
(
{
keyboard: true
}, 'show'
);
bindForm(this);
});
return false;
});
$(document).on("click", "a[data-modal]", function (e)
{
$('#myModalContent').load(this.href, function ()
{
$('#myModal').modal
(
{
keyboard: true
}, 'show'
);
bindForm(this);
});
return false;
});
$(window.document).on('shown.bs.modal', '.modal', function () {
window.setTimeout(function () {
$('[autofocus]', this).focus();
}.bind(this), 100);
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
var isValid = true; // assume all OK
$('form').validate(); // perform validation on the form
$('input[type="text"]').each(function (index, item) { // could change selector to suit e.g $('input, textarea').each(..
if (!$(this).valid()) {
isValid = false; // signal errors
return false; // break out of loop
}
});
if (!isValid) {
return false; // exit
}
$('#progress').show();
$.ajax({
url: this.action,
modal: true,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#myModal').modal('hide');
$('#progress').hide();
location.reload();
alert(result.message);
}
});
return false;
});
}
Question
When I call dialog form for Edit Company I get dialog form as on Image1.
After validation $('form').validate(); // perform validation on the form
I get dialog form as on Image2. Please help me understand what do I wrong?
Image1
Image2
In Controller
public ActionResult Edit([Bind(Include = ....] Company company)
Need to use return View(company); instead of return PartialView(company)
I'm working on a form in my application, which I want to post using ajax. The posting works fine and my controller receives the data, but I'd like to just post a success message back to my view instead of refreshing the entire page. Do I have to return a partial view with the information for this, or can I just return a message from my controller? I can't seem to figure out how to do this properly.
<div class="panel panel-gray">
<div class="panel-body">
<form method="POST" action="#Url.Action("SaveWellDetails", "WellManagement")" id="wellform" class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => m.Id, new { #class = "col-md-3 control-label"})
<div class="col-md-9">
#Html.TextBoxFor(m => m.Id, new { #class = "form-control", disabled = "disabled", id = "WellId", name = "WellId" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Name, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Location, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.Location, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.WellNumber, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.WellNumber, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.WellType, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.WellType, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.SpudDate, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.SpudDate, new { #class = "form-control" })
</div>
</div>
<div class="panel-footer">
<input type="submit" id="submit" class="btn btn-primary" value="Save Changes" />
<div class="pull-right" id="wellsavesection">
<div id="processing_small" hidden="hidden">
<img src="~/Content/Kendo/Flat/loading_2x.gif" />
</div>
</div>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#wellform').submit(function () {
console.log("wellId = " + $("#WellId").val());
$("#processing_small").show().hide().fadeIn('slow');
$.ajax({
url: '#Url.Action("SaveWellDetails", "WellManagement")',
type: "POST",
dataType: "json",
data: {
wellId: $('#WellId').val(),
name: $('#Name').val(),
location: $('#Location').val(),
wellNumber: $('#WellNumber').val(),
wellType: $('#WellType').val(),
spudDate: $('#SpudDate').val()
},
error: function (msg) {
$('#wellsavesection').hide().html('<div class="alert alert-danger"><strong>Ouch!</strong> ' + msg.statusText + '</div>').fadeIn('slow');
},
success: function (msg) {
$('#wellsavesection').hide().html('<div class="alert alert-success"><strong>Success!</strong> Form Saved.</div>').fadeIn('slow').delay(1500).fadeOut();
}
});
});
});
</script>
Here's my controller:
[HttpPost]
public ActionResult SaveWellDetails(string wellId, string name, string location, string wellNumber, string wellType, DateTime spudDate)
{
try
{
var wellConctract = new WellContract
{
Id = Convert.ToInt32(wellId),
Name = name,
Location = location,
WellNumber = wellNumber,
WellType = wellType,
SpudDate = spudDate
};
WellService.UpdateWell(wellConctract);
}
catch (Exception e)
{
Log.Error(e);
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message);
}
return Json(new {success = true}, JsonRequestBehavior.AllowGet);
}
Simply add return false; the end of the $('#wellform').submit(function () {... (after the ajax function, not inside it) and it should work, I tried it out in jsfiddle.
What this does it prevent the form from submitting.
you doesn't need a partial view to do that, your page will refresh each submit because it doing the usual event, try add event.preventDefault() http://api.jquery.com/event.preventdefault/
$('#wellform').submit(function (ev) {
ev.preventDefault();
// put your code below here
.....
});