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);
Related
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.
I have the following code where I use Ajax.Beginform:
<div class="modal-body" style="text-align: center;">
#using (Ajax.BeginForm("LogIn", "Home", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target",
OnSuccess = "ajaxSuccess"
}, null))
{
<div class="sign_up_container">
Email:<br />
#Html.EditorFor(x => x.Login.Email, new { htmlAttributes = new { #class = "sign_up_container_input_style" } })<br/>
#Html.ValidationMessageFor(x => x.Login.Email, null, new { #class = "text-danger" })
</div>
<div class="sign_up_container">
Password:<br />
#Html.EditorFor(x => x.Login.Password, new { htmlAttributes = new { #class = "sign_up_container_input_style" } })
<br/>Forgott password?
</div>
<div class="sign_up_container">
<br />
<button type="submit" class="btn_style_3 btn">Login</button>
</div>
}
</div>
The validation works. When I enter a invalid email and hits Login, unobtrusive kicks In and says that I must enter a valid Email.
However, now I want to show a message that says that the Username or password is invalid If the user enters a invalid username or password. I have tried to do like this in my LogIn-method:
[HttpPost]
public async Task<JsonResult> Login(homeIndexViewModel model)
{
if(!ModelState.IsValid)
{
return Json(new { ModelState = "Something went wrong during login" });
}
var user = await userManager.FindAsync(model.Login.Email, model.Login.Password);
if (user != null)
{
await SignIn(user);
//return Json(new { RedirectAction = GetRedirectUrl(model.Login.ReturnUrl, user.UserId) }, JsonRequestBehavior.AllowGet);
}
return Json(new { ModelState = "Invalid email or password" }, JsonRequestBehavior.AllowGet);
}
In my Index.cshtml I'm trying to catch the json like this:
$(document).ready(function () {
function ajaxSuccess(result) {
console.log(result); //Contains error message, show It
}
});
The problem I have is that when I hit Login, I'm redirected to a white page with a json-string printed out with the message:
I have a form in my webpage that asks for first and last name. When the user submits this form I would like the data to be passed to a function in my controller, where it is used to find the corresponding user in our Active Directory. I want to then return the matching Email address to a Javascript function, when then displays that information on my page. Is this the "correct" way to go about doing this, and if yes, how would I structure a function in my controller to accept form input, and return data to my client side javascript?
What I have so far in my controller:
public SearchResult[] searchAD(String fname, String lname)
{
Func<System.DirectoryServices.ActiveDirectory.Domain> domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain;
System.DirectoryServices.DirectoryEntry root = new DirectoryEntry("LDAP://"+domain);
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchRoot = root;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenName={0})(sn={1}))", fname, lname);
SearchResult[] results = new SearchResult['a'];
searcher.FindAll().CopyTo(results, 0);
return results;
}
And my form:
#using (Html.BeginForm("searchAD", "AD", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.firstName, "First Name", htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.firstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.firstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.lastName, "Last Name", htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.lastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.lastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div>
<input type="submit" value="Search" class="btn" />
</div>
</div>
}
You can Store value in TempData and get it on view
public ActionResult searchAD(String fname, String lname)
{
Func<System.DirectoryServices.ActiveDirectory.Domain> domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain;
System.DirectoryServices.DirectoryEntry root = new DirectoryEntry("LDAP://"+domain);
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchRoot = root;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenName={0})(sn={1}))", fname, lname);
SearchResult[] results = new SearchResult['a'];
searcher.FindAll().CopyTo(results, 0);
TempData["Result"]=results;
return View("ViewName");
}
In View (Jquery)
$(function(){
if ('#TempData["Result"]' != '')
{
// call your function here and pass TempData Value
}
});
Above is not perfect solution for your posted issue because tempdata or viewbag are not meant for that.If you need to post data again back from control to view then its always make use of #Ajax.BeginForm
#using (Ajax.BeginForm("ActionName", "Controller", new AjaxOptions { OnComplete = "Sucess" }))
in jquery you have to write Success function like below :
function Sucess(arg) {
//arg.data
}
in arg.data you will get that object what you are passing from controller.More ever #Html.BeginForm refreshing your whole page not specific content but with With Ajax.begin form you can manage to reload only those content which is under ajax.begin form.
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"});
}
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;
}