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"});
}
Related
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();
}
I have a page that contains a partial view, which has dynamically added form fields (name and date-range for each guest). How do I submit all these fields to a post method, so that I get a list of all the guests (name AND date-range)?
The partial view:
#model ProjectName.Models.ViewModels.GuestCreatorViewModel
#using Res = ProjectName.Resources.Resources
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#for (int i = 1; i <= Model.NumOfGuests; i++)
{
<div class="row">
<div class="form-group">
#Html.Label(Res.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(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.Label(Res.Period, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.DateRange, new { id = "dateRangePicker", #class = "form-control custom-date-picker", #readonly = true })
#Html.ValidationMessageFor(model => model.DateRange, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
<div class="form-group">
<div>
<input type="submit" value="#Res.CreateGuests" class="customBtnXSmall" />
</div>
</div>
</div>
}
<script type="text/javascript">
$('input.custom-date-picker').daterangepicker({
"showWeekNumbers": true
}, function (start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
});
</script>
I'm guessing that I can write some javascript or an AJAX function to post the information, since it's just strings, but I'm not sure how and I'm not that skilled with javascript.
Can anyone help me make a simple post action for these dynamic form fields?
The solution was actually really simple, and already implemented. I already used model binding to bind the data to a model, so instead of the model having "name" and "daterange" attributes as string, I just changed their type to List<string> and that way it fills all the values into those lists.
public ActionResult CreateGuests([Bind(Include = "Name,DateRange,NumOfGuests")] GuestCreatorViewModel viewModel)
public List<string> Name { get; set; }
public List<string> DateRange { get; set; }
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".
So i'm making a back End admin dashboard, and i'd like to add a functionality for current users to be able to change their passwords when they're logged in. Below is my relevant code for the Account Settings Page where the change password will be taking place.
The user information is all stored in a model database called LoginDataModel I just can't work out for the life of me how to get the current logged in user to be able to change his/hers own password and then log them out to be able to log in with the new password? I've even tried using the Edit part from the UserManagement CRUD application however still nothing.
public class UserManagementController : Controller
{
private UserDatabaseEntities db = new UserDatabaseEntities();
public ActionResult AccountSettings(int? id)
{
if (id == null)
{
return View();
}
Login login = db.Logins.Find(id);
if (login == null)
{
return HttpNotFound();
}
return View(login);
}
[HttpPost]
public ActionResult AccountSettings([Bind(Include = "Password")]Login login)
{
if (ModelState.IsValid)
{
User.Identity.GetUserId();
db.Entry(login).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(login);
}
}
#using (Html.BeginForm())
{
<div class="container col-sm-4 col-md-4 col-lg-4">
<div class="form-group">
<label for="AssemblyName">New Password :</label>
<div class="form-group" style="width: 300px;">
<div>
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", #placeholder = "New Password" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
</div>
<button type="submit" class="btn btn-info" style="width: 200px; "><span class="glyphicon glyphicon-plus-sign"></span>Save Changes</button>
Delete
</div>
}
Hope you can help!
If you are using asp identity and want to change password of user then first you need to create reset password token
string userId = User.Identity.GetUserId();
string token = await UserManager.GeneratePasswordResetTokenAsync(userId);
And then use that token to reset password
var result = await UserManager.ResetPasswordAsync(userId, token, newPassword);
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;
}