I have an APS.Net web app Razor view where I attempt to display the Viewbag.errormessage.
The action method populates the viewbag but the view does not show the error message that is in the viewbag. It does not appear. Why?
The paragraph to which the Viewbag is attached to does not even appear per the 2nd pic. In the 1st pic, I can see that is there.
I also tried using 'TempData' but it produces the same result - not appearing.
Here is the action method (simplified):
[HttpPost]
public async Task<ActionResult> DeleteUserAccount(string userName, string
password)
{
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
ViewBag.errormessage = "The 'user name' or 'password' is
invalid - empty. Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
ViewBag.errormessage = "Your 'user name' is invalid. It
is not the same as the 'user name' used at original sign
in. Please try again.";
}
}
}
catch (Exception ex1)
{
}
return View();
}
Here is the view:
#Html.AntiForgeryToken()
<div class="login-panel">
#if (ViewBag.errormessage != null)
{
<p class="alert alert-danger" id="errorMessage">#ViewBag.errormessage</p>
}
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/css")
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
$(".btn-yes4").click(function () {
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "User")',
data: { userName: holdUserName, password: holdPassword},
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
$("#myModal4").on('hidden.bs.modal', function () {
$("#myModal4").remove();
});
});
})
</script>
https://dotnetfiddle.net/U6HGHD
Ajax makes a call and does not re-render a page
Controller
[HttpPost]
//I made method snchronous as it has no await, and there are no resources to add await to
public ActionResult DeleteUserAccount(string userName, string password)
{
var errorMessage = String.Empty;
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
//since this method is ajax, the view will not re-render, so errors need
//to go into return value.
//ViewBag.errormessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
errorMessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
//ViewBag.errormessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
errorMessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
}
}
}
catch (Exception ex1){}
//return View();
//since this is ajax, I am returning a json
return Json(errorMessage, JsonRequestBehavior.AllowGet);
}
public ActionResult Index19()
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index19</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js" integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
//put this in here
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
//fixed the following line
});
$(".btn-yes4").click(function () {
//put these here
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "Home")',
data: { userName: holdUserName, password: holdPassword },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
if (data.length > 0) {
$("#errorMessage").css("display", "block");
}
else {
$("#errorMessage").css("display", "none");
}
$("#errorMessage").text(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
//$("#myModal4").on('hidden.bs.modal', function () {
// $("#myModal4").remove();
//});
});
</script>
</head>
<body>
#Html.AntiForgeryToken()
<div class="login-panel">
#*took out condition, and started with style none*#
#*#if (ViewBag.errormessage != null)
{*#
<p class="alert alert-danger" id="errorMessage" style="display:none">#ViewBag.errormessage</p>
#*}*#
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Related
I have 2 inputs boxes: Public key (user name) and Private key (password). Also I have a hidden warning label.
This is my code (and it's perfectly working ):
<script language="javascript">
function SendLoginData() {
document.getElementById("LoginErrorLabel").style.display = "none";
var url = "/DappAccount/CheckAccount";
$.post(url, { PublicKey: $("#public_key_input").val(), PrivateKey: $("#private_key_input").val() }, function (data) {
if (data == false) {
document.getElementById("LoginErrorLabel").style.display = "block";
return;
}
else {
document.getElementById("loader").style.display = "block";
$("#myform").submit()
}
});
}
</script>
<div class="container">
#using (Html.BeginForm("AccountMainPage", "DappAccount", FormMethod.Post, new { #id = "myform" }))
{
<div class="row justify-content-center">
#Html.TextBoxFor(m => m.publicKey, new { id = "public_key_input", placeholder = "Ethereum Public Key", required = "required" })
</div> <br />
<div class="row justify-content-center">
#Html.TextBoxFor(m => m.privateKey, new { id = "private_key_input", placeholder = "Ethereum Private Key", required = "required", type = "password" })
</div> <br />
<div class="row justify-content-center">
<img id="loader" style="display: none;" src="https://s5.gifyu.com/images/Loader5a73d3b26568dbc4.gif" alt="Loader5a73d3b26568dbc4.gif" border="0" />
</div> <br />
}
<div class="row justify-content-center">
<input id="submit" type="button" value="Login" class="btn btn-primary" onclick="SendLoginData()" />
</div>
<label id="LoginErrorLabel" style="color: red; display: none;">*Wrong login detail !</label>
</div>
What I'm doing here is:
1) Send username&password to the 'CheckAccount' method in the controller, the method returns true/false.
2) If false, show label,
if true, show gif image and send again the details to ActionResult (=AccountMainPage) which returns a new view.
I just wonder, is there a better/shorter way to do it using one post or one method? I heard something about the partial views in MVC, no idea what to do with it. People told me that what I did here is too old for MVC
I want to add a project name and task name while clicking on a particular date in fullcalendar but I don't know how to use bootbox.prompt or bootbox.dialog with more than one fields so can you help me out?
select: function (start, end, allDay) {
debugger;
bootbox.prompt("Add New Event", function (title) {
debugger;
if (title !== null) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay,
className: 'label-info'
},
true // make the event "stick"
);
}
});
It's quite simple, we can use bootbox dialog for that
bootbox.dialog({
title: 'Add New Event',
message: $('#form'),
show: false,
}).on("shown.bs.modal", function (e) {
$('#form').show()
}).on('hide.bs.modal', function (e) {
/**
* Bootbox will remove the modal (including the body which contains the login form)
* after hiding the modal
* Therefor, we need to backup the form
*/
$('#form').hide().appendTo('body');
})
.modal('show');
calendar.fullCalendar('unselect');
}
In html
<form id="form" method="post" class="form-horizontal" style="display: none;">
<div class="form-group">
<label class="col-xs-3 control-label">Username</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-primary" style="float:right;">Login</button>
</div>
</div>
I self admitted newbie, but I have a view with some code I pasted to provide a file upload. The function works but if the code is in, the "Save" button for the View that was already there stops working. If I had to guess it has something to do with the "HTML.BeginForm" line being there twice.
Here is the top of the view,
#model BrooksSOR.Models.dataOffender
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<div >
<h2>Upload Files in MVC</h2>
<img src="#Model.Photograph" width="250" height="250" />*
#using (Html.BeginForm("FileUpload", "SOR",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File"/>
<input type="hidden" name="parmPersonID" value="#Model.PersonID" />
}
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>dataOffender</legend>
<p>
<input type="submit" value="Save" />
<input id="Details" type="button" value="Details" />
</p>
</fieldset>
Remove the #html.BeginForm
The script you would need to send for a file and some other fields with it.
//Purpose: Form Submit: SAVE Client
document.getElementById('frmPage').onsubmit = function (e) {
debugger;
var file = document.getElementById('fileToUpload').files[0];
var filename;
if (file) {
filename = file.name;
}
else {
filename = "";
}
$('#Image').val(filename);
var formObj = $(this);
var formURL = '#Url.Action("SaveMethod", "ControllerName")';
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function (data, textStatus, jqXHR) {
debugger;
alert("Client saved successfully");
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
e.preventDefault(); //Prevent Default action.
}
This is the design:
<div>
<form id="frmPage" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label id="lblImage" class="col-md-3 control-label">Upload File</label>
<div class="col-md-4">
<input type="file" id="fileToUpload" name="file" />
</div>
</div>
<div class="modal-footer" style="margin-top: 0px">
<div class="pull-right">
<button type="submit" id="btnSave" class="btn blue Save">Save</button>
</div>
</div>
</form>
</div>
Here: The btnSave is submit type, so it will submit that particular form. and form named frmPage will do the jquery script we added.
Update:
I have replaced <input type=submit to <button ... and also remove the form tag from my html, after modifying my code i do not see it executing my JS and I have a debugger line in the code and it does not break....
I'm trying to POST data and I have all the code in placed and wired-up correctly (I believe) but when I try to Submit my page # My page gets refreshed, I don't see any event is firing and I have set debugger in the JS, and I do not see any JS error in developer tool
What I'm missing here apart from my code?
here is my code:
//HML code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My AngularJS App</title>
<script src="../AppScripts/RequesterAdd.js"></script>
</head>
<body>
<form>
<div ng-app="requesterAddModule" ng-controller="requesterAddController" class="container">
<h2> add requester</h2>
<div ng-show="ShowMessage">Record saved Successfully</div>
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HostModel</h4>
<hr />
<div class="form-group">
<div>First Name:</div>
<div class="col-md-10">
<input type="text" ng-model="FirstName" required class="form-control input-lg" placeholder="First Name" />
</div>
</div>
<div class="form-group">
<div>Middle Name:</div>
<div class="col-md-10">
<input type="text" ng-model="MiddleName" required class="form-control input-lg" placeholder="Middle Name" />
</div>
</div>
<div class="form-group">
<div>Last Name:</div>
<div class="col-md-10">
<input type="text" ng-model="LastName" required class="form-control input-lg" placeholder="Last Name" />
</div>
</div>
<div class="form-group">
<div>eMail Address:</div>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="text" ng-model="Email" required class="form-control input-lg" placeholder="Email Address" />
</div>
</div>
<div class="form-group">
<div>Is Host Active:</div>
<div class="col-md-10">
<input type="checkbox" ng-model="Active" required class="control-label col-md-2" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</form>
</body>
</html>
//JS:
var requesterAddModule = angular.module("requesterAddModule", []);
requesterAddModule.factory('requesterAddService',
['$http', function ($http) {
return {
addRequester: function (reqesterData) {
console.log(reqesterData);
debugger;
$http({
url: 'PersistRequester',
method: 'POST',
data: reqesterData
}).then (function (response) {
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
},
function(response) {
//failed
}
);
}
};
}]);
requesterAddModule.controller('requesterAddController', ['$scope', '$http', '$window', 'requesterAddService', function ($scope, $http, $window, requesterAddService) {
$scope.addRequester_ClickEvent = function () {
var req = {};
debugger;
req["FirstName"] = $scope.FirstName;
req["MiddleName"] = $scope.MiddleName;
req["LastName"] = $scope.LastName;
req["Email"] = $scope.Email;
req["Active"] = $scope.Active;
requesterAddService.addRequester(req);
}
}]);
//MVC Server side code:
[HttpPost]
public JsonResult PersistRequester(Requester requester)
{
var req = requester;
//if (ModelState.IsValid)
// {
req.CreatedDateTime = DateTime.Now;
db.Requesters.Add(requester);
db.SaveChanges();
return Json(new { Status = "Success" });
//}
}
You're using a form without a method and action which will by default post to the current url. I would highly recommend not to use a form or at least not using an <input type="submit" /> which will default in all the browsers to submit the form.
You're clearly using Bootstrap 3 here so why not just remove the form tag and the submit button and replace it with another element which will not trigger the form post and style it with class="btn btn-primary". Some could argue against this practise along the graceful degradation guidelines but since this particular form is not built from ground up to support the non-js scenario, it is best not to allow browser submit at all.
Also, in your service where you're doing the actual post, you specifically tell the page to reload.
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
You should pass this data back to the viewmodel so that the view can re-render and display the response.
If you change the url, the view state is lost and the page will simply render again to the initial state.
instead line
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
please do
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" class="btn btn-primary" >Create</button>
I've just tested and is working for me replace:
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
with
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" value="Create" class="btn btn-primary" >submit</button>
and I've change a bit your service to :
requesterAddModule.factory('requesterAddService',
['$http', function ($http)
{
return {
addRequester: function (reqesterData)
{
console.log(reqesterData);
debugger;
$http.post('PersistRequester', reqesterData).then(function (response)
{
if (response !== 'undefined' && typeof (response) == 'object') {
window.location.href = '/'
}
},
function (response)
{
//failed
}
);
}
};
}]);
it's posting to /home/PersistRequester if method 'PersistRequester' exist in other controller ie : foo controller change
$http.post('PersistRequester', reqesterData).then(function (response)
to $http.post('foo/PersistRequester', reqesterData).then(function (response)
This is what is getting sent to the server:
http://localhost:3182/Admin/UserAdmin/Save?Count=0&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D
I am using the unobtrusive jquery.unobtrusive-ajax and it is working fine on other pages in my project. I am not doing anything fancy with the BeginForm helper. It is pretty straight forward actually. I can post it if it helps, but there is not much too it.
I thought another library might be interfering with my code so I removed other scripts and it still does the same thing. It is very weird. Has anyone seen this before and know how to fix it?
Here is the entire view:
#using YogaDiVita.Ui.Helpers
#model YogaDiVita.Domain.YogaDiVitaContext.Model.User
#{
ViewBag.Title = "Profile";
Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
var isInstructor = (bool)ViewBag.IsInstructor;
}
<link href="#Url.ContentArea("~/Scripts/plugins/fineUploader/fineuploader.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Scripts/plugins/jCrop/css/jquery.Jcrop.min.css")" rel="stylesheet"
type="text/css" />
<div class="row-fluid">
<div class="span12">
<h3 class="heading">User Profile</h3>
<div class="row-fluid">
<div class="span8">
#using (Ajax.BeginForm("Save",new RouteValueDictionary(), new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure"
}, new { #class = "form-horizontal well" }))
{
#Html.HiddenFor(u => u.Id)
#Html.HiddenFor(u => u.CreatedById)
#Html.HiddenFor(u => u.ModifiedById)
#Html.HiddenFor(u => u.Username)
#Html.Hidden("isInstructor", isInstructor)
<fieldset>
<div class="control-group formSep">
<label class="control-label">
Username</label>
<div class="controls text_line">
<strong>#Model.Username</strong> Reset Password
</div>
</div>
<div class="control-group formSep">
<label for="fileinput" class="control-label">
User avatar</label>
<div class="controls">
<div data-fileupload="image" class="fileupload fileupload-new">
<div style="width: 80px; height: 80px;" class="fileupload-new thumbnail">
<img src="http://www.placehold.it/108x108/EFEFEF/AAAAAA " alt="" id="userAvatar">
</div>
<a href="/Admin/UserAdmin/ImageUpload/#Model.Id" class="btn avatarUpload">Upload New
Image</a>
</div>
</div>
</div>
<div class="control-group formSep">
<label for="FirstName" class="control-label">
First Name</label>
<div class="controls">
#Html.TextBoxFor(u => u.FirstName, new { #class = "input-xlarge" })
</div>
</div>
<div class="control-group formSep">
<label for="FirstName" class="control-label">
Last Name</label>
<div class="controls">
#Html.TextBoxFor(u => u.LastName, new { #class = "input-xlarge" })
</div>
</div>
<div class="control-group formSep">
<label for="u_email" class="control-label">
Email Address</label>
<div class="controls">
#Html.TextBoxFor(u => u.EmailAddress, new { #class = "input-xlarge" })
</div>
</div>
<div class="control-group formSep">
<label for="u_email" class="control-label">
Telephone Number</label>
<div class="controls">
#Html.TextBoxFor(u => u.TelephoneNumber, new { #class = "input-xlarge" })
</div>
</div>
<div class="control-group formSep">
<label for="u_email" class="control-label">
Mobile Number</label>
<div class="controls">
#Html.TextBoxFor(u => u.MobileTelephoneNumber, new { #class = "input-xlarge" })
</div>
</div>
<div class="control-group formSep">
<label for="u_email" class="control-label">
Mobile Number</label>
<div class="controls">
#Html.TextBoxFor(u => u.MobileTelephoneNumber, new { #class = "input-xlarge" })
</div>
</div>
<div class="control-group formSep">
<label for="u_email" class="control-label">
Is Instructor</label>
<div class="controls">
#Html.CheckBox("cbIsInstructor", isInstructor)
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-gebo" type="submit">
Save changes</button>
</div>
</div>
</fieldset>
}
</div>
</div>
</div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"
type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/plugins/jcrop/jquery.Jcrop.min.js")" type="text/javascript"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/util.js")"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/button.js")"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/handler.base.js")"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/handler.form.js")"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/handler.xhr.js")"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/uploader.basic.js")"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/dnd.js")"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/uploader.js")"></script>
<script src="#Url.ContentArea("~/Scripts/plugins/fineUploader/jquery-plugin.js")"></script>
<script>
$(function () {
loadUserAvatar();
$('.avatarUpload').colorbox({
initialHeight: '520',
initialWidth: '650',
iframe: false,
opacity: 0.45,
onClosed: function () {
loadUserAvatar();
}
});
$('.resetPasswordWindow').colorbox({
initialHeight: '0',
initialWidth: '0',
iframe: false,
opacity: 0.45,
onClosed: function () {
},
onComplete: function () {
$.validator.addMethod("passwordsMustMatch", function (value, element) {
return $('#validatePassword').val() == $('#password').val();
}, "The passwords do not match");
$('.resetPasswordForm').validate({
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
errorPlacement: function (error, element) {
error.appendTo(element.closest("div.controls"));
},
highlight: function (element) {
$(element).closest("div.control-group").addClass("error f_error");
var thisStep = $(element).closest('form').prev('ul').find('.current-step');
thisStep.addClass('error-image');
},
unhighlight: function (element) {
$(element).closest("div.control-group").removeClass("error f_error");
if (!$(element).closest('form').find('div.error').length) {
var thisStep = $(element).closest('form').prev('ul').find('.current-step');
thisStep.removeClass('error-image');
};
},
rules: {
password: { required: true, minlength: 6, passwordsMustMatch: true },
validatePassword: { required: true, minlength: 6, passwordsMustMatch: true }
},
invalidHandler: function (form, validator) {
$.sticky("There are some errors. Please corect them and submit again.", { autoclose: 5000, position: "top-right", type: "st-error" });
}
});
}
});
});
function loadUserAvatar(parameters) {
$.ajax({
url: '/Admin/Avatar/AvatarLoad/#Model.Id',
type: 'POST',
cache: false,
timeout: 100000,
error: function (xhr, status, error) {
alert(error + " " + status);
},
success: function (data) {
$("#userAvatar").attr("src", data.Image.ThumbNailRelativePath);
}
});
}
function OnSuccess(parameters) {
$.sticky("The user profile has been updated successfully.", { autoclose: 5000, position: "top-right", type: "st-error" });
}
function OnFailure(parameters) {
$.sticky("There was an error saving the profile. </br>" + parameters.message, { autoclose: 5000, position: "top-right", type: "st-error" });
}
</script>
UPDATE:
After a little research at what as happening, I was getting this error after the post: An item with the same key has already been added
You can't bind directly to Collections - see ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries for examples of how to accomlish what you are trying to do.
Well, i figured out the issue. Kind of silly really. The issue was I had an interface on my Model. There were 2 version of the property Username. One was named UserName (with a capital N) and the other was Username (lowercase n). This blog post helped.