Knockout.js wizard validation on each step - asp.net-mvc-3

I have managed to create a simple wizard based on an answer given by Niemeyer. This works fine. I want to add validation. I have managed to add a required validion on the field Firstname. Leaving this empty displays an error. But what I could not succeed in is the following:
Validate the model in the current step, and have the go next enabled or disabled based whether there are errors. If it is too difficult to enable or disable the next button, that is ok. I can also live without the button disabled when there are errors. As long as the user is prevented to proceed to the next step when there are errors.
. My view looks like this:
//model is retrieved from server model
<script type="text/javascript">
var serverViewModel = #Html.Raw(Json.Encode(Model));
</script>
<h2>Test with wizard using Knockout.js</h2>
<div data-bind="template: { name: 'currentTmpl', data: currentStep }"></div>
<hr/>
<button data-bind="click: goPrevious, enable: canGoPrevious">Previous</button>
<button data-bind="click: goNext, enable: canGoNext">Next</button>
<script id="currentTmpl" type="text/html">
<h2 data-bind="text: name"></h2>
<div data-bind="template: { name: getTemplate, data: model }"></div>
</script>
<script id="nameTmpl" type="text/html">
<fieldset>
<legend>Naamgegevens</legend>
<p data-bind="css: { error: FirstName.hasError }">
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, new { data_bind = "value: FirstName, valueUpdate: 'afterkeydown'"})
<span data-bind='visible: FirstName.hasError, text: FirstName.validationMessage'> </span>
</p>
#Html.LabelFor(model => model.LastName)
#Html.TextBoxFor(model => model.LastName, new { data_bind = "value: LastName" })
</fieldset>
</script>
<script id="addressTmpl" type="text/html">
<fieldset>
<legend>Adresgegevens</legend>
#Html.LabelFor(model => model.Address)
#Html.TextBoxFor(model => model.Address, new { data_bind = "value: Address" })
#Html.LabelFor(model => model.PostalCode)
#Html.TextBoxFor(model => model.PostalCode, new { data_bind = "value: PostalCode" })
#Html.LabelFor(model => model.City)
#Html.TextBoxFor(model => model.City, new { data_bind = "value: City" })
</fieldset>
</script>
<script id="confirmTmpl" type="text/html">
<fieldset>
<legend>Naamgegevens</legend>
#Html.LabelFor(model => model.FirstName)
<b><span data-bind="text:NameModel.FirstName"></span></b>
<br/>
#Html.LabelFor(model => model.LastName)
<b><span data-bind="text:NameModel.LastName"></span></b>
</fieldset>
<fieldset>
<legend>Adresgegevens</legend>
#Html.LabelFor(model => model.Address)
<b><span data-bind="text:AddressModel.Address"></span></b>
<br/>
#Html.LabelFor(model => model.PostalCode)
<b><span data-bind="text:AddressModel.PostalCode"></span></b>
<br/>
#Html.LabelFor(model => model.City)
<b><span data-bind="text:AddressModel.City"></span></b>
</fieldset>
<button data-bind="click: confirm">Confirm</button>
</script>
<script type='text/javascript'>
$(function() {
if (typeof(ViewModel) != "undefined") {
ko.applyBindings(new ViewModel(serverViewModel));
} else {
alert("Wizard not defined!");
}
});
</script>
The knockout.js implementation looks like this:
function Step(id, name, template, model) {
var self = this;
self.id = id;
self.name = ko.observable(name);
self.template = template;
self.model = ko.observable(model);
self.getTemplate = function() {
return self.template;
};
}
function ViewModel(model) {
var self = this;
self.nameModel = new NameModel(model);
self.addressModel = new AddressModel(model);
self.stepModels = ko.observableArray([
new Step(1, "Step1", "nameTmpl", self.nameModel),
new Step(2, "Step2", "addressTmpl", self.addressModel),
new Step(3, "Confirmation", "confirmTmpl", {NameModel: self.nameModel, AddressModel:self.addressModel})]);
self.currentStep = ko.observable(self.stepModels()[0]);
self.currentIndex = ko.dependentObservable(function() {
return self.stepModels.indexOf(self.currentStep());
});
self.getTemplate = function(data) {
return self.currentStep().template();
};
self.canGoNext = ko.dependentObservable(function () {
return self.currentIndex() < self.stepModels().length - 1;
});
self.goNext = function() {
if (self.canGoNext()) {
self.currentStep(self.stepModels()[self.currentIndex() + 1]);
}
};
self.canGoPrevious = ko.dependentObservable(function() {
return self.currentIndex() > 0;
});
self.goPrevious = function() {
if (self.canGoPrevious()) {
self.currentStep(self.stepModels()[self.currentIndex() - 1]);
}
};
}
NameModel = function (model) {
var self = this;
//Observables
self.FirstName = ko.observable(model.FirstName).extend({ required: "Please enter a first name" });;
self.LastName = ko.observable(model.LastName);
return self;
};
AddressModel = function(model) {
var self = this;
//Observables
self.Address = ko.observable(model.Address);
self.PostalCode = ko.observable(model.PostalCode);
self.City = ko.observable(model.City);
return self;
};
And I have added an extender for the required validation as used in the field Firstname:
ko.extenders.required = function(target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};

This was a tricky one, but I'll offer a couple of solutions for you...
If you simply want to prevent the Next button from proceeding with an invalid model state, then the easiest solution I found is to start by adding a class to each of the <span> tags that are used for displaying the validation messages:
<span class="validationMessage"
data-bind='visible: FirstName.hasError, text: FirstName.validationMessage'>
(odd formatting to prevent horizontal scrolling)
Next, in the goNext function, change the code to include a check for whether or not any of the validation messages are visible, like this:
self.goNext = function() {
if (
(self.currentIndex() < self.stepModels().length - 1)
&&
($('.validationMessage:visible').length <= 0)
)
{
self.currentStep(self.stepModels()[self.currentIndex() + 1]);
}
};
Now, you may be asking "why not put that functionality in the canGoNext dependent observable?", and the answer is that calling that function wasn't working like one might thing it would.
Because canGoNext is a dependentObservable, its value is computed any time the model that it's a member of changes.
However, if its model hasn't changed, canGoNext simply returns the last calculated value, i.e. the model hasn't changed, so why recalculate it?
This wasn't vital when only checking whether or not there were more steps remaining, but when I tried to include validation in that function, this came into play.
Why? Well, changing First Name, for example, updates the NameModel it belongs to, but in the ViewModel, self.nameModel is not set as an observable, so despite the change in the NameModel, self.nameModel is still the same. Thus, the ViewModel hasn't changed, so there's no reason to recompute canGoNext. The end result is that canGoNext always sees the form as valid because it's always checking self.nameModel, which never changes.
Confusing, I know, so let me throw a bit more code at you...
Here's the beginning of the ViewModel, I ended up with:
function ViewModel(model) {
var self = this;
self.nameModel = ko.observable(new NameModel(model));
self.addressModel = ko.observable(new AddressModel(model));
...
As I mentioned, the models need to be observable to know what's happening to them.
Now the changes to the goNext and goPrevious methods will work without making those models observable, but to get the true real-time validation you're looking for, where the buttons are disabled when the form is invalid, making the models observable is necessary.
And while I ended up keeping the canGoNext and canGoPrevious functions, I didn't use them for validation. I'll explain that in a bit.
First, though, here's the function I added to ViewModel for validation:
self.modelIsValid = ko.computed(function() {
var isOK = true;
var theCurrentIndex = self.currentIndex();
switch(theCurrentIndex)
{
case 0:
isOK = (!self.nameModel().FirstName.hasError()
&& !self.nameModel().LastName.hasError());
break;
case 1:
isOK = (!self.addressModel().Address.hasError()
&& !self.addressModel().PostalCode.hasError()
&& !self.addressModel().City.hasError());
break;
default:
break;
};
return isOK;
});
[Yeah, I know... this function couples the ViewModel to the NameModel and AddressModel classes even more than simply referencing an instance of each of those classes, but for now, so be it.]
And here's how I bound this function in the HTML:
<button data-bind="click: goPrevious,
visible: canGoPrevious,
enable: modelIsValid">Previous</button>
<button data-bind="click: goNext,
visible: canGoNext,
enable: modelIsValid">Next</button>
Notice that I changed canGoNext and canGoPrevious so each is bound to its button's visible attribute, and I bound the modelIsValid function to the enable attribute.
The canGoNext and canGoPrevious functions are just as you provided them -- no changes there.
One result of these binding changes is that the Previous button is not visible on the Name step, and the Next button is not visible on the Confirm step.
In addition, when validation is in place on all of the data properties and their associated form fields, deleting a value from any field instantly disables the Next and/or Previous buttons.
Whew, that's a lot to explain!
I may have left something out, but here's the link to the fiddle I used to get this working: http://jsfiddle.net/jimmym715/MK39r/
I'm sure that there's more work to do and more hurdles to cross before you're done with this, but hopefully this answer and explanation helps.

Related

Returning ValidationSummary in Partial View to Ajax error handler - nothing else getting rendered

I'm calling a method from Ajax that updates a some content in the page by loading up a partial view & setting a contained property appropriately.
This all works ok but I'm having problems with server side validation using the ValidationSummary control. I'm using an approach suggested elsewhere to stick the ValidationSummary in a partial view. (I've actually got client side validation turned off & I'm trying to get server side validation to work using the same validation summary that client side validation uses)
When there is a validation error, ajax error handler should update the contents of a div with the partial view that is returned.
All this works ok in the sense that the validation summary is rendered with the expected error messages except for the fact that the nothing else is getting displayed on the page other than the partial view containing the validation summary and its containing elements. i.e. no siblings / of the div are getting rendered
I reaslly haven't got a clue what's going on. Intersetingly, if I comment out the line in the error handler that updates the div with the partial, I see the form in its entirety again.
I'm using an ExceptionFilter:
public class ValidationErrorAttribute : FilterAttribute, IExceptionFilter
{
public virtual void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.Exception != null)
{
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.HttpContext.Response.StatusCode =
(int)System.Net.HttpStatusCode.BadRequest;
//return the partial view containing the validationsummary and set the ViewData
//so that it displays the validation error messages
filterContext.Result = new PartialViewResult { ViewName = "validation",
ViewData = filterContext.Controller.ViewData };
}
}
}
when there's a validation error, throw a validationexception which will
trigger the OnException method of the filter
//Controller
[HttpPost]
[ValidationErrorAttribute]
public ActionResult Save(ConsumptionData consumptionData)
{
if (ModelState.IsValid)
{
var dto = Mapper.Map<ConsumptionData, ConsumptionDataDto>(consumptionData);
var refId = _personalProjectionRepository.AddPersonalProjectionRecord(dto);
consumptionData.ReferenceId = refId;
return PartialView("Reference", consumptionData);
}
else
{
throw new ValidationException();
}
}
The validation partial view:
#model PersonalProjection.Web.Models.ConsumptionData
#Html.ValidationSummary()
and the jquery:
$('form').submit(function () {
var form = $(this);
if (form.valid())
{
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "html",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
SiteId: $('#siteid').val(),
ElectricityConsumption: $('#electricityconsumption').val(),
ElectricitySpend: $('#electricityspend').val(),
GasConsumption: $('#gasconsumption').val(),
GasSpend: $('#gasspend').val()
}),
success: function (result) {
$('#rightPanelSection').html(result);
},
error: function (jqXHR) {
$('#validationSummary').html(jqXHR.responseText);
}
});
}
return false;
});
and the index.cshtml markup
<div class="panel panel-outcome">
#using (Html.BeginForm("Save", "Home", FormMethod.Post, (object)new { ID =
"projectionForm" }))
{
<div id="validationSummary"/>
<div id="topPanelSection" class="panel-section">
#Html.LabelFor(m => m.SiteId, new { id = "siteidlabel" })
#Html.TextBoxFor(m => m.SiteId, ViewBag.TextBoxDisabled ? (object)new { id =
"siteid", disabled = true, maxlength = 9, #class = "input-disabled", #Value =
ViewBag.SiteId } : new { id = "siteid", maxlength = 9 })
<span id="errorText" class="error-text" />
</div>
<div id="leftPanelSection" class="panel-section">
<div class="column-heading">
<span class="column-heading-left">Total Cost</span>
<span class="column-heading-right">Total Consumption</span>
</div>
<div class="panel-section-row">
#Html.LabelFor(m => m.ElectricitySpend, new { id = "electricitylabel" })
<span>£</span>
#Html.TextBoxFor(m => m.ElectricitySpend, new { #class = "textbox-right-
margin", id = "electricityspend" })
#Html.TextBoxFor(m => m.ElectricityConsumption, new { #class = "textbox-
left-margin", id = "electricityconsumption" })
<span>kWhs</span>
</div>
<div class="panel-section-row">
#Html.LabelFor(m => m.GasSpend, new { id = "gaslabel" })
<span>£</span>
#Html.TextBoxFor(m => m.GasSpend, new { #class = "textbox-right-margin", id =
"gasspend" })
#Html.TextBoxFor(m => m.GasConsumption, new { #class = "textbox-left-margin",
id = "gasconsumption" })
<span>kWhs</span>
</div>
<div class="panel-section-row">
<button type="reset" id="resetbutton">Reset Form</button>
<button type="submit">Generate Reference Id</button>
</div>
</div>
<div id="rightPanelSection" class="panel-section">
#Html.Partial("Reference", Model)
</div>
}
I'm fairly new to Ajax so this is probably a schoolboy error but here goes:
It's because when I use this jquery
$('#validationSummary').html(jqXHR.responseText);
To update this
<div id="validationSummary"/>
it doesn't like the closing tag & it messes up
Change to this
<div id="validationSummary">
</div>
And it works ok.

Jquery Accordion Validation Not working when rendering Partial View through $.ajax call

Hi friends,I am working on MVC 4 Razor and I am stuck in a situation
where Employee Personal Details form is to be filled in
steps(wizard)..for which i used jquery accordion control..for every
step i put an accordion..The html in each accordion section is
rendered from partial view through ajax call on every click of
respective accordion (i.e. <h3></h3> tag)..
On page load first/top accordion is active by default. My problem is
to restrict the user to click on next accordion until he/she fills the
presently active accordion correctly..
Here is my full code:
View:
#model XXX.ViewModels.PersonalDetailsViewModel
#{
ViewBag.Title = "PersonalDetails";
Layout = "~/Views/Shared/Template.cshtml";
}
#using (Html.BeginForm("Lifestyle", "Apply", FormMethod.Post, new { id = "personalDetailForm" }))
{
<div class="centerdiv margin_top20">
<div class="row">
#Html.ValidationSummary(true, "Please Correct the following errors:")
</div>
<div style="width: 1000px;">
<div id="Personalaccordion" class="acordion_div" style="padding: 10px; float: left;">
<h3 class="acordion_div_h3" onclick="javascript:PersonalModule.GetRenderingView('Apply/GetBasicDetailsView','personalDetailForm','BasicDetailsDiv');">
<p>
Basic Details<span id="BasicDetailsDivExp"></span>
</p>
</h3>
<div id="BasicDetailsDiv">
</div>
<h3 class="acordion_div_h3" onclick="javascript:PersonalModule.GetRenderingView('Apply/GetPersonalAddressView','personalDetailForm','PersonalAddressDiv');">
<p>
Address<span id="PersonalAddressDivExp"></span></p>
</h3>
<div id="PersonalAddressDiv">
</div>
</div>
<ul id="conlitue_ul" style="margin-top: 20px;">
<li style="margin-left: 140px;">
<input type="submit" class="compareBtn float_lt" value="Continue Buying >" id="continue" /></li>
</ul>
</div>
</div>
}
#Scripts.Render("~/bundles/PersonalDetails")
<script type="text/javascript">
PersonalModule.GetRenderingView('Apply/GetBasicDetailsView', '', 'BasicDetailsDiv');
</script>
My Controller:
public ActionResult PersonalDetails(int leadId)
{
var personalDetailsViewModel = LeadHelper.GetPersonalDetails(leadId);
return View(personalDetailsViewModel);
}
public ActionResult GetBasicDetailsView(PersonalDetailsViewModel personalDetailsViewModel)
{
if (personalDetailsViewModel.BasicDetails == null)
{
ModelInitializerHelper.InitilaizeBasicDetailsVModel(personalDetailsViewModel);
}
ModelInitializerHelper.InitializeBasicLookup(personalDetailsViewModel);
return PartialView("Personal/BasicDetails", personalDetailsViewModel);
}
public ActionResult GetPersonalAddressView(PersonalDetailsViewModel personalDetailsViewModel)
{
if (personalDetailsViewModel.PersonalAddressDetails == null)
{
ModelInitializerHelper.IntializePersonalAddressVModel(personalDetailsViewModel);
}
ModelInitializerHelper.InitializePersonalAddressLookup(personalDetailsViewModel);
return PartialView("Personal/PersonalAddress", personalDetailsViewModel);
}
My JS :
var PersonalModule = {
GetRenderingView: function (url, formId, containerID) {
var applicationurl = ApplicationRoot + '/' + url;
var objects = $('#BasicDetailsDivExp , #PersonalAddressDivExp' );
viewDivID = containerID;
GetAccordionView(applicationurl, formId, objects, containerID, 'accordion_plus', 'accordion_minus');
}
}
GetAccordionView: function (url, formId, objects, containerID, accordion_plus, accordion_minus) {
var formObjectData = null;
if (formId != undefined) {
formObjectData = $("#" + formId).serialize();
}
var renderView = function (data) {
$('#' + containerID).innerHtml = data;
}
ExpandAccordion(objects, containerID, accordion_plus, accordion_minus);
DoServerRequest(url, formObjectData, renderView);
}
ExpandAccordion: function (objects, spanIconID, accordion_plus, accordion_minus) {
var Objects = objects;
Objects.removeClass(accordion_minus);
Objects.addClass(accordion_plus);
$('#' + spanIconID + 'Exp').removeClass(accordion_plus).addClass(accordion_minus);
if (Browser.ie7) {
Objects.css("margin-top", "-22px");
}
}
DoServerRequest: function (url, data, funSuccess) {
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
dataType: "json",
success: funSuccess,
error: function (errorResponse) {
if (errorResponse.readyState == 4 && errorResponse.status == 200) {
renderCurrentView(errorResponse.responseText)
}
else {
alert(errorResponse.responseText);
}
}
});
}
Please somebody help..I have heard lots of good thing about this forum
and this is my first Question...Thanks in advance..
I have removed my jquery validation attempt as it made the code
garbage thing Now I dont know what to write and where to write
If you are trying to validate data that has been added to form via Ajax after page load then you will need to use the rules method and add rules for these new elements. Jquery Validate has no way of knowing about them otherwise.
Example
Once you have loaded your new content via Ajax you need to find each element and add the necessary rules to them.
$('#yourDiv').find(".newElements").rules("add", {
required: true,
messages: {
required: "Bacon is required"
}
});
If you are using unobtrusive validate you may need to add your new elements to that also. See this SO question for more details.
Validating the Form
To check if the fields are valid, you will need to validate the form on click. This can be done using .validate(). You can then check if the form validated using .valid()
Example
$('#yourForm').validate();
if(!$('#yourForm').valid()) {
alert('Bacon is required');
}

Ajax form submission with Valums plugins in asp.net mvc 3

I have used Valums uploader plugins for file uploads in asp.net mvc 3. Following is the views which have form fields and ajax query upload button inside form. I am not sure that I am doing it right or not. What I have to change on view so that When I Choose the file to upload the form field's value is also send.
Views:
<link href="#Url.Content("~/Content/css/fileuploader.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Content/js/fileuploader.js")" type="text/javascript"></script>
#using (Html.BeginForm("Upload","AjaxUpload")) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Upload Image File</legend>
<div class="editor-label">
#Html.Label("Select Language")
</div>
<div>
#Html.DropDownList("Language1", (SelectList) ViewBag.lang)
</div>
<div class="editor-label">
#Html.Label("Select Category")
</div>
<div>
#Html.DropDownList("ParentCategoryID", ViewBag.ParentCategoryID as SelectList)
</div>
<div id="file-uploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
</fieldset>
}
**<script type="text/javascript">
var uploader = new qq.FileUploader
({
element: document.getElementById('file-uploader'),
action: '#Url.Action("upload")', // put here a path to your page to handle uploading
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'], // user this if you want to upload only pictures
sizeLimit: 4000000, // max size, about 4MB
minSizeLimit: 0 // min size
});
</script>**
How Can I passed the value of form to controller of HTTPOST Action So that I can save data to the database. Here, I have Upload action which save the data in database but I don't know to retrieve to those value send by form post.
HttpPost Action
[HttpPost]
public ActionResult Upload(HttpPostedFileBase qqfile)
{
var wav = new PlayWav
{
Name = ***filename***,
CategoryID = ***value from category dropdown select list***,
UserID = repository.GetUserID(HttpContext.User.Identity.Name),
LanguageID = int.Parse(***value from language dropdown select list***),
UploadDateTime = DateTime.Now,
ActiveDateTime = DateTime.Now,
FilePath = "n/a"
};
if (qqfile != null)
{
// this works for IE
var filename = Path.Combine(Server.MapPath("~/App_Data/Uploads"), Path.GetFileName(qqfile.FileName));
qqfile.SaveAs(filename);
return Json(new { success = true }, "text/html");
}
else
{
// this works for Firefox, Chrome
var filename = Request["qqfile"];
if (!string.IsNullOrEmpty(filename))
{
filename = Path.Combine(Server.MapPath("~/App_Data/Uploads"), Path.GetFileName(filename));
using (var output = System.IO.File.Create(filename))
{
Request.InputStream.CopyTo(output);
}
**db.PlayWavs.Attach(wav);
db.SaveChanges();**
return Json(new { success = true });
}
}
return Json(new { success = false });
}
Didn't you read the documentation? There's a whole section entitled Sending additional params. Even an example is given:
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/server-side.upload',
// additional data to send, name-value pairs
params: {
param1: 'value1',
param2: 'value2'
}
});

View or Hide a dropdownlist in my razor view using helper method

I have an object named Visit and i defined the following helper method (“CanBeEdited”) to specify if users can edit the object Status property or not:-
public partial class Visit
{
public bool CanBeEdited(string username)
{return (((DoctorID != null) && (DoctorID.ToUpper().Equals(username.ToUpper()))) && (StatusID == 5)); } }}
Then i have specified to show or hide certain dropdownlist on my Edit view depending on weather the CanBeEdited helper method returns true or false (if it returns true then the user can view and edit the Status dropdownlist, and if it returns false then the view will render an #Html.HiddenFor representing the old status value).
My edit view which includes the helper method looks as following:-
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Visit</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Note)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Note)
#Html.ValidationMessageFor(model => model.Note)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DoctorID)
</div>
<div class="editor-field">
#Html.DropDownList("DoctorID", String.Empty)
#Html.ValidationMessageFor(model => model.DoctorID)
</div>
#{
if (Model.CanBeEdited(Context.User.Identity.Name))
{
<div class="editor-label">
#Html.LabelFor(model => model.StatusID)
</div>
<div class="editor-field">
#Html.DropDownList("StatusID", String.Empty)
#Html.ValidationMessageFor(model => model.StatusID)
</div>
}
else
{
#Html.HiddenFor(model => model.StatusID)}
}
<p>
#Html.HiddenFor(model => model.VisitTypeID)
#Html.HiddenFor(model => model.CreatedBy)
#Html.HiddenFor(model => model.Date)
#Html.HiddenFor(model => model.VisitID)
#Html.HiddenFor(model => model.PatientID)
#Html.HiddenFor(model => model.timestamp)
<input type="submit" value="Create" />
</p>
</fieldset>
}
To be honest it is the first time i implement such as case,, so is my approach sound valid ???,, or it have some weaknesses i am unaware of ??. As i need to implemented similar cases all around my web application...
Baring in mind that i am also checking for the CanBeEdited on the action methods..
Thanks in advance for any help.
Updated:-
My post action method look as follow:-
[HttpPost]
public ActionResult Edit(Visit visit)
{
if (!(visit.Editable(User.Identity.Name)))
{
return View("NotFound");
}
try
{
if (ModelState.IsValid)
{
repository.UpdateVisit(visit);
repository.Save();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var clientValues = (Visit)entry.Entity;
ModelState.AddModelError(string.Empty, "The record you attempted to edit "
+ "was modified by another user after you got the original value. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again. Otherwise click the Back to List hyperlink.");
// patient.timestamp = databaseValues.timestamp;
}
catch (DataException)
{
//Log the error (add a variable name after Exception)
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
}
ViewBag.DoctorID = new SelectList(Membership.GetAllUsers(), "Username", "Username", visit.DoctorID);
ViewBag.StatusID = new SelectList(db.VisitStatus, "StatusID", "Description", visit.StatusID);
ViewBag.VisitTypeID = new SelectList(db.VisitTypes, "VisitTypeID", "Description", visit.VisitTypeID);
return View(visit);
}
I don't feel adding that in the View is a good idea. I would like to have My ViewModel to hold a property of boolean type to determine that it is editable or not. The value of that you can set in your controller after checking the relevant permissions.
public class ProductViewModel
{
public bool IsEditable { set;get;}
//other relevant properties
}
and controller action
public ActionResult GetProduct()
{
ProductViewModel objVM=new ProductViewModel();
objVm.IsEditable=CheckPermissions();
}
private bool CheckPermissions()
{
//Check the conditions and return true or false;
}
So view will be clean like ths
#if (Model.IsEditable)
{
//Markup for editable region
}
IMHO, it sounds valid enough.
UPDATE: removed irrelevant commentary, and edited to indicate a primary concern.
Now, taking a closer look, especially with the controller action, I strongly recommend that you eliminate the hidden fields (except the one that you need to re-load the record from your back end).
A savvy user can tamper with the hidden form data (all the form data) and your controller action will happily send it all back to the server.
In reality, you should post back only the fields that are permitted to be changed, rehydrate the record from the back end, and transfer the "editable" fields to the fresh copy. This also comes closer to addressing concurrent edit and stale record issues.

jQuery unobtrusive validation in .NET MVC 3 - showing success checkmark

Using jQuery unobtrusive validation within a .NET MVC project and that seems to be working fine. I'm now trying to show a green checkmark when the field validates correctly (client-side and/or remote).
Here's a sample field declaration:
<div class="clearfix">
#Html.LabelFor(model => model.Address1, "Street")
<div class="input">
#Html.TextBoxFor(model => model.Address1, new { #class = "xlarge", #maxlength = "100", #placeholder = "e.g. 123 Main St" })
<span class="help-message">
#Html.ValidationMessageFor(model => model.Address1)
<span class="isaok">Looks great.</span>
</span>
<span class="help-block">Enter the street.</span>
</div>
</div>
What I'd like to do is add a class 'active' to the "span.isaok" which in turn has a checkmark for a background image.
I tried using highlight/unhighlight:
$.validator.setDefaults({
onkeyup: false,
highlight: function (element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
$(element.form).find("label[for=" + element.id + "]").addClass("error");
$(element).parent().find("span.isaok").removeClass("active");
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass);
$(element.form).find("label[for=" + element.id + "]").removeClass("error");
if ($(element).val().length > 0) {
$(element).parent().find("span.isaok").addClass("active");
}
}
});
but that shows a green checkmark for all fields even if they're empty! (hence obviously wrong)
I then tried using the 'success' option but that never seems to be fired.
What am I missing?
Edit: So I found this blog post and was able to tap into the success function i.e.
$(function () {
var settings = $.data($('form')[0], 'validator').settings;
settings.onkeyup = false;
settings.onfocusout = function (element) { $(element).valid(); };
var oldErrorFunction = settings.errorPlacement;
var oldSuccessFunction = settings.success;
settings.errorPlacement = function (error, inputElement) {
inputElement.parent().find("span.isaok").removeClass("active");
oldErrorFunction(error, inputElement);
};
settings.success = function (label) {
var elementId = '#' + label.attr("for");
$(elementId).parent().find("span.isaok").addClass("active");
oldSuccessFunction(label);
};
});
but now if the form isn't valid it shows both the error message and the valid mark...
and the latter disappears as soon as I click anywhere on the page.
This appears to be an issue with the jquery.validate.unobtrusive interfering with the settings added later in $.validator.setDefault. The trick is to load the unobtrusive script after the custom settings. See here and vote to fix it here.
In case any one has a similar problem, I finally got this working by using the un-minified version of jquery.validate.unobtrusive.js and adding my js to the onError and onSuccess methods. Existing code was left as it. Use the re-minified version during deployment.
Thanks.
This is not a direct answer to your question. I am going to offer an alternative approach to this: TwitterBootstrapMVC.
With this library all you'd have to write for each input is:
#Html.Bootstrap().ControlGroup().TextBoxFor(m => m.Address1)
And that's it. You will have label, input, and validation message - all taken care of, without javascript. It generates proper html mark up for you. You just need to make sure that you have proper standard css for classes like .field-validation-error, .field-validation-valid...

Resources