Validate user input against the DB value - javascript

I am build my first .NET Core MVC application and using the Entity Framework. I have a edit page where users are allowed to enter the Quantity that they would like to order. The model classes are like below
public partial class Inventory
{
public string Name { get; set; }
public int QuantityAvailable { get; set; }
public string RoomNumber { get; set; }
public int InventoryId { get; set; }
[NotMapped]
public int? QuantityReq { get; set; }
}
and
public class Item
{
public int CustomId { get; set; }
public Inventory Inventory { get; set; }
}
The QuantityReq doesnot exists in the DB so I added them as NotMapped. So I have a view name is AddtoOrder on the Item like
#model JAXSurplusMouseApp.Models.Item
#{
ViewData["Title"] = "Edit";
}
<h4>Add to Order</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="AddtoOrder">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="#Model.Inventory.Name" class="control-label"></label>
<input asp-for="#Model.Inventory.Name" class="form-control" readonly />
</div>
<div class="form-group">
<label asp-for="#Model.Inventory.QuantityAvailable" class="control-label"></label>
<input asp-for="#Model.Inventory.QuantityAvailable" class="form-control" readonly />
</div>
<div class="form-group">
<label asp-for="#Model.Inventory.RoomNumber" class="control-label"></label>
<input asp-for="#Model.Inventory.RoomNumber" class="form-control" readonly />
</div>
</form>
<form method="post"
asp-controller="Inventories"
asp-action="OrderItem">
<label class="control-label">Quantity Required</label>
<input type="text" id="quantityReq" name="quantityReq" value=#Model.Inventory.QuantityReq />
<input type="hidden" id="customerID" name="customerID" value="#Model.CustomId" />
<input type="hidden" id="invetoryID" name="invetoryID" value="#Model.Inventory.InventoryId" />
<button type="submit"><u>Order</u></button>
</form>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
The Controller action is like below, if the user entering the quantity is more than the Quantity that is available then the order is placed and it navigates back to the other page. But if users enter a number in the Quantity required that is more than the Quantity Available then I need to post a error message in the same page that they have entered invalid quantity
// Action to launch the AddtoOrder page
public async Task<IActionResult> AddtoOrder(int? inventoryID, int? custID)
{
if (inventoryID == null || custID == null)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(custID);
var inventories = await _context.Inventories.FindAsync(inventoryID);
var model = new Item
{
CustomId = (int)custID,
Inventory = inventories
};
return View(model);
}
//Action athat allows the users to submit the order
public async Task<IActionResult> OrderItem(int? customerID, int? invetoryID, int quantityReq)
{
if (customerID == null || invetoryID == null)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(invetoryID);
if (quantityReq <= intData.QuantityAvailable && quantityReq > 0)
{
InventoryOrder io = new InventoryOrder();
io.OrderQuantity = quantityReq;
io.InventoryId = (int)invetoryID;
_context.Add(io);
await _context.SaveChangesAsync();
intData.QuantityAvailable = intData.QuantityAvailable - quantityReq;
_context.Update(intData);
await _context.SaveChangesAsync();
return RedirectToAction("Index", "Inventories", new { id = customerID });
}
else if (quantityReq > intData.QuantityAvailable){
How to redirect to the same page back with the validation error
}
}

first of all you should add #Html.ValidationSummary(false, "", new { #class = "error" }) to your form. Also, I would recommend you use HTML Helpers.
This is simple example of form:
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
#Html.LabelFor(m => m.Age)
#Html.TextBoxFor(m => m.Age)
<input type="submit" value="Submit"/>
#Html.ValidationSummary(false, "", new { #class = "error" })
}
And then you can custom validate your model and send error to View:
// Validation logic
else if (quantityReq > intData.QuantityAvailable)
{
ModelState.AddModelError("QuantityReq", "QuantityReq more than QuantityAvailable");
return View();
}

Related

How to properly validate form using jquery Unobtrusive Validation?

I am trying to use jquery unobtrusive validation in my form, and no matter if the html inputs are empty or not, the validation message is always showing as soon as I open the page. The HTML is in a handlebars template. I am using HttpPost to retrieve data when loading the page.
My View:
<form id="submitForm" class="form">
<section id="conferenceContainer"></section>
<div id="saveBtnContainer">
<input type="submit" id="saveBtn" class="btn" value="Submit" />
<div id="lblCheckContainer">
<label id="lblCheck"></label>
</div>
</div>
</form>
<script type="text/x-handlebars-template" id="conferenceTemplate">
<div id="newConference">
<div class="form-group row">
#Html.LabelFor(x => x.ConferenceTitle,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.ConferenceTitle,
new { #id="confTitle", #class="form-control", #Value= "{{ConferenceTitle}}" })
#Html.ValidationMessageFor(x => x.ConferenceTitle, "*Enter a conference title*", new { #class="text-danger" })
</div>
<div class="form-group row">
#Html.LabelFor(x => x.EventDate,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.EventDate,
new { #id="confDate", #class="form-control", #Value="{{formatDate EventDate}}" })
#Html.ValidationMessageFor(x => x.EventDate, "*Enter the date of the conference*", new { #class="text-danger" })
</div>
<div class="form-group row">
#Html.LabelFor(x => x.RegFullPrice,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.RegFullPrice,
new { #id="confPrice", #class="form-control", #Value="{{RegFullPrice}}" })
#Html.ValidationMessageFor(x => x.RegFullPrice, "*Enter the price to register for conference*", new { #class="text-danger" })
</div>
<div class="form-group row">
#Html.LabelFor(x => x.PreRegEndDate,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.PreRegEndDate,
new { #id= "confPreRegDate", #class="form-control", #Value= "{{formatDate PreRegEndDate}}" })
#Html.ValidationMessageFor(x => x.PreRegEndDate, "*Enter the last day to pre-register for conference*", new { #class="text-danger" })
</div>
<div class="form-group row">
#Html.LabelFor(x => x.PreRegDiscount,
new { #class="confLabels" })
#Html.TextBoxFor(x => x.PreRegDiscount,
new { #id= "confPreRegDiscount", #class="form-control", #Value= "{{PreRegDiscount}}" })
#Html.ValidationMessageFor(x => x.PreRegDiscount, "*Enter the discount for pre-registration*", new { #class = "text-danger" })
</div>
</div>
</script>
I am handling the submit input in .ready function where 'saveData()' is a method with the ajax call.
<script type="text/javascript">
var setup = new ConferenceSetup();
$(document).ready(function () {
setup.GetData();
$('#submitForm').submit(function () {
var confirmSave = confirm("Are you finished editing the Conference?");
if (confirmSave) {
setup.SaveData();
event.preventDefault();
} else {
event.preventDefault();
}
});
});
</script>
It seems I have the server side validation working but I cannot get the client side to act like I want.
My model:
[DisplayName("Conference Title")]
[Required]
public string ConferenceTitle { get; set; }
[DisplayName("Event Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd", ApplyFormatInEditMode = true)]
[Required]
public DateTime EventDate { get; set; }
[DisplayName("Registration Price")]
[Range(0, 999.99, ErrorMessage = "Price must be between $0 and $1,000")]
[Required]
public decimal RegFullPrice { get; set; }
[DisplayName("Pre-Registration End Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd", ApplyFormatInEditMode = true)]
[Required]
public DateTime PreRegEndDate { get; set; }
[DisplayName("Pre-Registration Discount")]
[Range(0, 999.99, ErrorMessage = "Discount must be between $0 and $1,000")]
[Required]
public decimal PreRegDiscount { get; set; }
My Controller:
[Authorize]
public class ConfSetupController : Controller
{
public ActionResult NewConf()
{
ConferenceModel model = new ConferenceModel();
return View(model);
}
This is what my page looks like, the validation messages never go away
Any help or suggestions is greatly appreciated!
To hide the validation on page load check if .field-validation-error and .validation-summary-valid css class "display" property is set to "none".

How to send client data to MVC controller for Login page?And save to database?

Login.cshtml
<script type="text/javascript">
function data() {
var n = document.getElementById("username").value;
var m = document.getElementById("password").value;
?
</script>
<button type="submit"class="btn-login" onClick="Data()">
Giriş Yap </button>
Account Controller
DBEntities dB = new DBEntities();
[HttpPost] (username) (password)
public ActionResult Login(string KullaniciAdi,string Sifre)
{
// Session[KullaniciAdi] = dB.Profil.Where(x => x.KullaniciAdi == KullaniciAdi && x.Sifre == Sifre).FirstOrDefault();
var session = (from p in dB.Profil
where p.KullaniciAdi == KullaniciAdi
select p).FirstOrDefault();
return View();
}
My OOP homework is this website and i want to create a login with sending password and username to controller and compare submitted data and the data in the database .Please help :)
You can send client data by using ajax request,
this is your inputs
<input id="username" type="text" />
<input id="password" type="password" />
<input id="loginbutton" onclick="UserLogin()" type="submit" value="Submit" />
Submit button bind with UserLogin js function.
here is the js function. we are sending ajax post request here to our controller
<script type="text/javascript">
function UserLogin() {
var n = document.getElementById("username").value;
var p = document.getElementById("password").value;
var postObj = JSON.stringify({
"username": n,
"password": p
});
$.ajax({
url: "/Home/Login", // endpoint
type: "POST",
data: postObj,
contentType: "application/json; charset=utf-8",
success: function (result) {
// success
},
error: function (errorData) { onError(errorData); }
});
}
</script>
And your controller should be like, you can implement login logic inside of the method.
[HttpPost]
public ActionResult Login(string username, string password)
{
// use your code loged in
return Json(true, JsonRequestBehavior.AllowGet);
}
First You Create a Class :
public class LoginModel
{
[Required(ErrorMessage = "User Name can not be empty!")]
public string LOGINID { get; set; }
[Required(ErrorMessage = "Password can not be empty!")]
public string LOGINPW { get; set; }
}
Then Your Controller Action Method do this:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//Here check the Login Id and Password
return View();
}
Now in view Write this. Now when you click the submit button a post call go to the Login Controller with given LOGINID and LOGINPW :
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<!-- login screen -->
<form action="#">
#Html.TextBoxFor(m => m.LOGINID, htmlAttributes: new { #class = "form-control", placeholder = "Login ID" })
#Html.ValidationMessageFor(model => model.LOGINID, "", new { #class = "text-danger", style = "float: left" })
#Html.PasswordFor(m => m.LOGINPW, htmlAttributes: new { #class = "form-control", placeholder = "Password" })
#Html.ValidationMessageFor(model => model.LOGINPW, "", new { #class = "text-danger", style = "float: left" })
<button type="submit" class="btn btn-primary" style="background: #2e6da4; color: #FFF;">Login</button>
</form>
}
#{
var actionURL = Url.Action("Action", "Controller",
FormMethod.Post, Request.Url.Scheme)
+ Request.Url.PathAndQuery;
}
#using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { #action = actionURL }))
{
<input type="text" name="username">
<input type="text" name="password">
<button type="submit"class="btn-login"></button>
}//Then use Request.Form[0] with the id to get the user name and password in the controller action.

Asp.Net MVC submit button doesn' t post values to my method in Controller while using onclick javascript function for validation

When I am saving my data for the first time (when clicked on save button of my view) then I am getting value of submitButton variable in my controller action. But when I am editing my view and then click on save then I am getting null value in submitButton variable in my controller action.
My View Model
public class TermiViewModel : ViewModelBase
{
public long Id { get; set; }
public string Name { get; set; }
}
My View
#model TermiViewModel
#using (Html.BeginForm("MyActionMethod", "MyController", FormMethod.Post))
{
#Html.HiddenFor(model => model.Id)
<div>
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
</div>
<button name="submitButton" value="Save" type="submit"
onclick="return JavaScriptFunction();">Save</button>
<button name="submitButton" value="Cancel" type="submit"
onclick="return JavaScriptFunction();">Cancel</button>
}
Below is the Javascript I am using in my view.
<script language="javascript" type="text/javascript">
function JavaScriptFunction() {
return true;
}
</script>
Below is my Controller class.
public class MyController : CoreMvcController
{
private readonly ITermiRepositoryService _termiRepository;
public MyController(ITermiRepositoryService termiRepository)
{
_termiRepository = termiRepository;
}
}
Below is my action Method where I am getting values from my view.
[HttpPost]
public ActionResult MyActionMethod(TermiViewModel termiViewModel, string submitButton)
{
try
{
voucherViewModel =_termiRepository.Save(termiViewModel);
switch (submitButton)
{
case "Cancel":
return RedirectToAction("Edit",termiViewModel.Id);
default:
return RedirectToAction("Index");
}
}
catch (Exception exception)
{
}
return RedirectToAction("Index");
}
In my above Controller method I get the null value for my submitButton variable while editing my view. I don't understand why I am getting null value because while creating for the first time, I am getting values of submitButton from the submit button.
Thanks for any help!
For the solution, I need to change following classes:
My View Model:
// A new property "SaveButtonValue" added to my view model.
public class TermiViewModel : ViewModelBase
{
public long Id { get; set; }
public string Name { get; set; }
public string SaveButtonValue { get; set; }
}
My View:
// Added a hidden field for "SaveButtonValue" and passing this keyword in
// Javascript function for onclick of submit button.
#model TermiViewModel
#using (Html.BeginForm("MyActionMethod", "MyController", FormMethod.Post))
{
#Html.HiddenFor(model => model.Id)
#Html.HiddenFor(model => model.SaveButtonValue)
<div>
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
</div>
<button name="submitButton" value="Save" type="submit"
onclick="return JavaScriptFunction(this);">Save</button>
<button name="submitButton" value="Cancel" type="submit"
onclick="return JavaScriptFunction(this);">Cancel</button>
}
Javascript:
// Populating my property "SaveButtonValue" through javascript
<script language="javascript" type="text/javascript">
function JavaScriptFunction(submitButton)
{
if (objButton) {
$('#SaveButtonValue').val(submitButton.value);
}
return true;
}
</script>
My action method:
[HttpPost]
public ActionResult MyActionMethod(TermiViewModel termiViewModel)
{
try
{
voucherViewModel =_termiRepository.Save(termiViewModel);
switch (termiViewModel.SaveButtonValue)
{
case "Cancel":
return RedirectToAction("Edit",termiViewModel.Id);
default:
return RedirectToAction("Index");
}
}
catch (Exception exception)
{
}
return RedirectToAction("Index");
}

ajax POST not passing back correct data

I am trying to pass back a json object back to my action in my device controller, this is then inserted into the database, however when I click the submit button on my form it seems to fire twice. Another problem is that my location field within the json object and pfID does not get sent back to the controller, the other fields get sent back properly. Here is my code:
$('#getDevice').unbind('click').bind('click', function (e) {
e.stopPropagation();
//anti forgery token
//get the form
var form = $('#addDeviceForm');
//from the form get the antiforgerytoken
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = 'Devices/PushIPForCollection';
//Before this we need to build the model from the input the user has given us
var device = {
deviceID: ' ',
ipAddress: $('#dIPAddress').val(),
deviceName: $('#dDeviceName').val(),
CreatedDate: ' ',
UpdatedDate: ' ',
CreatedBy: ' ',
UpdatedBy: ' ',
deviceSubGroupID: $('#dSubgroup option:selected').val(),
subgroup: " ",
companyID: ' ',
hidden: ' ',
pfID: $('#dpfID option:selected').val(),
pf: ' ',
location: JSON.stringify({
'region': $('#dRegion').val() == null ? ' ' : $('#dRegion').val(),
'country': $('#dCountry').val() == null ? ' ' : $('#dCountry').val(),
'city': $('#dCity').val() == null ? ' ' : $('#dCity').val(),
'building': $('#dBuilding').val() == null ? ' ' : $('#dBuilding').val(),
'room': $('#dRoom').val() == null ? ' ' : $('#dRoom').val(),
'rack': $('#dRack').val() == null ? ' ' : $('#dRack').val()
})
};
alert(device.pfID);
alert(device.location);
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
device: device
},
type: 'POST',
success: function (result) {
},
error: function (jqXHR, textStatus, errorThrown) {
alert("An error has occurred please contact us");
}
})
$('#add-device').modal('hide');
return false;
});
Where I alert my pfID it returns a string of "ba4475ef-0eed-441a-a77e-d733c288bf8e"
Here is my model:
public class Devices
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int deviceID { get; set; }
[Display(Name="IP Address:"), StringLength(50)]
public string ipAddress { get; set; }
[Display(Name = "DeviceName:"), StringLength(50)]
public string deviceName { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? UpdatedDate { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
[Display(Name="Add to subgroup:")]
public long? deviceSubGroupID { get; set; }
[ForeignKey("deviceSubGroupID")]
public DeviceSubGroup subgroup { get; set; }
public string companyID { get; set; }
public string hidden { get; set; }
public string pfID { get; set; }
[ForeignKey("pfID")]
public PfHealth.Pf pf { get; set; }
public string location { get; set; }
}
and here is my post method:
public ActionResult PushIPForCollection(Devices device)
{
//Before committing to the database we need to check if the device already exists
var checkIfDeviceExists = db.devices.Any(check => check.ipAddress == device.ipAddress);
if (!checkIfDeviceExists)
{
if (ModelState.IsValid)
{
var userID = User.Identity.GetUserId();
device.CreatedDate = DateTime.Now;
device.UpdatedDate = DateTime.Now;
device.CreatedBy = userID;
device.UpdatedBy = userID;
var subgroup = db.deviceSubGroups.Where(sub => sub.deviceSubID == device.deviceSubGroupID).FirstOrDefault();
device.communityString = subgroup.snmpCommunityString;
device.companyID = subgroup.companyID;
db.devices.Add(device);
db.SaveChanges();
}
}
//Can change this to get json in order to let to view know what message to display to the user.
return RedirectToAction("index");
}
and here is my form in the view:
<div class="modal fade" id="add-device" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="add-device-Label"><strong>ADD DEVICE</strong></h4><!--add depending on which panel you have clicked-->
</div>
<div class="modal-body" id="add-device-body">
<!--Depending on which panel insert content-->
#using (Html.BeginForm("PushIPForCollection", "Devices", FormMethod.Post, new { id = "addDeviceForm" }))
{
#Html.AntiForgeryToken()
<hr />
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-3">
#Html.LabelFor(m => m.device.ipAddress, new { #class = "col-md-2 control-label"})
</div>
<div class="col-md-9">
#Html.TextBoxFor(m => m.device.ipAddress, new { #class = "form-control", #id = "dIPAddress" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.LabelFor(m => m.device.deviceName, new { #class = "col-md-2 control-label" })
</div>
<div class="col-md-9">
#Html.TextBoxFor(m => m.device.deviceName, new { #class = "form-control", #id = "dDeviceName" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.LabelFor(m => m.device.deviceSubGroupID, new { #class = "col-md-2 control-label" })
</div>
<div class="col-md-9">
#Html.DropDownListFor(m => m.device.deviceSubGroupID, (IEnumerable<SelectListItem>)ViewBag.subGroups, "None", new { #id = "dSubgroup" })
#Html.ValidationMessageFor(m => m.device.deviceSubGroupID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Region:")
</div>
<div class="col-md-9">
#Html.TextBox("Region", "", new { #class = "form-control", #id = "dRegion" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Country:")
</div>
<div class="col-md-9">
#Html.TextBox("Country", "", new { #class = "form-control", #id = "dCountry" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("City:")
</div>
<div class="col-md-9">
#Html.TextBox("City", "", new { #class = "form-control", #id = "dCity" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Building:")
</div>
<div class="col-md-9">
#Html.TextBox("Building", "", new { #class = "form-control", #id = "dBuilding" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Room:")
</div>
<div class="col-md-9">
#Html.TextBox("Room", "", new { #class = "form-control", #id = "dRoom" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.Label("Rack:")
</div>
<div class="col-md-9">
#Html.TextBox("Rack", "", new { #class = "form-control", #id = "dRack" })
</div>
</div>
<div class="form-group">
<div class="col-md-3">
#Html.LabelFor(model=>model.device.pfID)
</div>
<div class="col-md-9">
#Html.DropDownListFor(m => m.device.pfID, (IEnumerable<SelectListItem>)ViewBag.pathfinders, "None", new { #id = "dpfID" })
#Html.ValidationMessageFor(m => m.device.pfID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="getDevice" type="submit" value="CreateGroups" data-loading-text="Loading..." class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
You do not need to create the javascript object manually, You may use jQuery serialize method to serialize the entire form and send it via ajax as long as the form field names matches with the param names/model property names in the HttpPost action method.
You may create a view model specific to the view.
public class CreateDeviceVm
{
public string DeviceId {set;get;}
public string IPAddress {set;get;}
public int DeviceSubGroupId {set;get;}
public List<SelectListItem> DeviceSubGroups {set;get;}
public string City {set;get;}
public string Room {set;get;}
//Add properties NEEDED FOR THE VIEW.
}
In your GET action, create an object of this view model, assign the DeviceSubGroups property and send to the view.
public ActionResult Create()
{
var vm = new CreateDeviceVm();
vm.DeviceSubGroups = db.DeviceSubGroups
.Select(s=> new SelectLisItem { Value=s.Id.ToString(),
Text = s.Name }).ToList();
return View(vm);
}
And in your view, which is strongly typed to the view model,
#model CreateDeviceVm
#using(Html.BeginForm())
{
<label>DeviceId</label>
#Html.TextBoxFor(s=>s.DeviceId)
<label>IP Address</label>
#Html.TextBoxFor(s=>s.IPAddress)
<label>Sub group</label>
#Html.DropDownListFor(s=>s.DeviceSubGroups,Model.DeviceSubGroups,"Select")
<label>City</label>
#Html.TextBoxFor(s=>s.City)
<label>Room</label>
#Html.TextBoxFor(s=>s.Room)
<input type="submit" id="btnSave" />
}
Now you can add some javascript to listen to the click event on the submit button, get a reference to the form, serialize it and send to the server using jQuery ajax.
$(function(){
$("#btnSave").click(function(e){
e.preventDefault();
var _f=$(this).closest("form");
$.post(_f.attr("action")._f.serialize(),function(res){
//check res and do something
});
});
});
And in your HttpPost action method,
[HttpPost]
public ActionResult Create(CreateDeviceVm model)
{
var exists= db.devices.Any(x=> x.ipAddress == model.ipAddress);
if (!exists)
{
var d= new Device();
d.IpAddress=model.IPAddress;
d.DeviceSubGroupId=model.DeviceSubGrouId;
//Map other properties as well.
db.Devices.Add(d);
db.SaveChanges();
return Json( new { status="success"});
}
return Json( new { status="failed"});
}

Validation in Partial view inside popup

I'm working in MVC and i have one scenario as follows:
I have a view called ManageResource where i il show the available resource's in grid and a button to add new resource. if i click on the add new resource button a popup il open with the partialview inside it, i have to display the validation result in popup itself when i click save with out entering any values and when i enter the required fields the values should be populated in the grid and the popup should be closed.`
"iam not getting validation result in popup, but can able to save data's"
following is my code:
Model-tblUser
public partial class tblUser
{
public int UID { get; set; }
[Required]
public int EmpID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public decimal Salary { get; set; }
}
View-ManageResource
function Create() {
BootstrapDialog.show({
title: "Add Resource",
message: $('<div id="CreatePopup"></div>').load('#Url.Action("Create", "Resource")')
});
return false;
}
<input type="button" id="AddNewCompany" onclick="Create()" class="push_button blue btn_width" value="Add New Resource" />
partial view- Create
function SaveResource() {
var obj = [];
var EmpID = $('#EmpID').val();
var FirstName = $('#FirstName').val();
var LastName = $('#LastName').val();
var Salary = $('#Salary').val();
if ($("#IsActive").attr('checked', true)) {
var IsActive = 1;
}
else {
var IsActive = 0
}
var newrecord = {
"EmpID": EmpID, "FirstName": FirstName, "LastName": LastName, "Salary": Salary,
};
var senddata = JSON.stringify(newrecord);
jQuery.ajax({
type: "POST",
url: '#Url.Action("Create", "Resource")',
data: JSON.stringify({ "data": senddata }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result == true) {
window.location.href = '#Url.Action("ManageResource", "Resource")';
} else {
$("#CreatePopup").html(result);
}
}
});
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false)
<div class="form-group">
#Html.LabelFor(model => model.EmpID, "Employee ID", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.EmpID)
#Html.ValidationMessageFor(model => model.EmpID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName,"First Name", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName,"Last Name", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-10">
<input type="button" id="CreateResource" onclick="SaveResource()" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Resource Controller
public PartialViewResult Create(string data)
{
JObject o = JObject.Parse(data);//parsing the json data
tblUser tbluser = new tblUser(); //creating instance for model tblUser
if ((string)o["EmpID"] != "" && (string)o["FirstName"] != "")// if all the required fields are present then add to db
{
db.tblUsers.Add(tbluser);//assign values here
tbluser.EmpID = (int)o["EmpID"];
tbluser.FirstName = (string)o["FirstName"];
tbluser.FirstName = (string)o["FirstName"];
tbluser.LastName = (string)o["LastName"];
tbluser.EmailID = (string)o["EmailID"];
tbluser.Password = (string)o["Password"];
tbluser.RoleID = (int)o["RoleID"];
tbluser.DeptID = (int)o["DeptID"];
tbluser.DesignationID = (int)o["DesignationID"];
tbluser.Salary = (int)o["Salary"];
tbluser.IsActive = (bool)o["IsActive"];
tbluser.CreatedBy = 121;
tbluser.CreatedDate = System.DateTime.Now;
tbluser.UpdatedBy = 121;
tbluser.UpdatedDate = System.DateTime.Now;
db.SaveChanges();
return RedirectToAction("ManageResource");//return to main view when saved
}
else
{
//return with validation summary to partialview popup
return PartialView(tbluser);
}
}
When you load a form using AJAX you need to tell jQuery unobtrusive validation to add the validation data- properties to the form elements. You need to add: $.validator.unobtrusive.parse('#YourFormSelector');
after the .load is completed.
function Create() {
BootstrapDialog.show({
title: "Add Resource",
message: $('<div id="CreatePopup"></div>').load('#Url.Action("Create","Resource")'
, function() {$.validator.unobtrusive.parse('#YourFormSelector');})
});
return false;
}

Categories