MVC5: Check DropDownList for having Selection (InvalidOperationException)? - c#

I am using BootStrap Switch to show/hide 2 Html.DropDownLists() on one of my MVC5/EF6 Project Views:
<input type="checkbox" value="12345" name="Sponsor-Organization" checked class="userCreate-BSSwitch" />
<div style="margin-bottom: 15px">
<div class="row switchOn">
<div class="editor-label">
#Html.LabelFor(model => model.MemberOrgId, "Organization")
</div>
<div class="editor-field">
#Html.DropDownList("MemberOrgId", ViewData["Organization"] as SelectList, String.Empty, new { #class = "form-control", #id = "MemberOrgId" })
#Html.ValidationMessageFor(model => model.MemberOrgId)
</div>
</div>
<div class="row switchOff">
<dliv class="editor-label">
#Html.LabelFor(model => model.SponsorOrgId, "Sponsor")
</dliv>
<div class="editor-field">
#Html.DropDownList("SponsorOrgId", ViewData["Sponsor"] as SelectList, String.Empty, new { #class = "form-control", #id = "SponsorOrgId" })
#Html.ValidationMessageFor(model => model.SponsorOrgId)
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script type="text/javascript">
jQuery(document).ready(function () {
setTimeout(function () { $("#alert").alert('close'); }, 5000);
$('.switchOff').addClass('hide');
});
$.fn.bootstrapSwitch.defaults.state = '';
$.fn.bootstrapSwitch.defaults.onText = 'Member';
$.fn.bootstrapSwitch.defaults.offText = 'Sponsor';
$.fn.bootstrapSwitch.defaults.offColor = 'info';
$.fn.bootstrapSwitch.defaults.animate = false;
//$.fn.bootstrapSwitch.defaults.size = 'large';
$(document).ready(function () {
$('input:checkbox[name="Sponsor-Organization"]').bootstrapSwitch();
});
$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function (event, state) {
var checked = state;
if (checked) {
$('.switchOn').removeClass('hide');
$('.switchOff').addClass('hide');
$('#SponsorOrgId').val("");
}
else {
$('.switchOff').removeClass('hide');
$('.switchOn').addClass('hide');
$('#MemberOrgId').val("");
}
});
$(document).ready(function () {
$(".btn-danger").click(function () {
var cancel = confirm("Are you sure? Entered data will be lost.")
if (cancel != true) {
event.preventDefault(); // cancel the event
}
});
});
//$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function(event, state) {
</script>
Controller Create() Method:
// POST: Admin/UserManagement/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,property1, property2, etc...")] ApplicationUser applicationUser)
{
if ((applicationUser.MemberOrgId == null) && (applicationUser.SponsorOrgId == null))
{
ModelState.AddModelError("", "Must select either an Organization or Sponsor from the dropdown lists.");
return View(applicationUser);
}
if (ModelState.IsValid)
{
ViewBag.headerTitle = "Create User";
applicationUser.UserName = applicationUser.Email;
IdentityResult result = await UserManager.CreateAsync(applicationUser, "r#nd0mP#$S");
if (result.Succeeded)
{
await db.SaveChangesAsync();
return RedirectToAction("Index", "UserManagement");
}
else
{
ModelState.AddModelError("", "Failed to Create User.");
var errors = string.Join(",", result.Errors);
ModelState.AddModelError("", errors);
}
}
ModelState.AddModelError("", "Failed to Create User.");
var errors1 = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToString();
ModelState.AddModelError("", errors1);
ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name", applicationUser.MemberOrgId);
ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name", applicationUser.SponsorOrgId);
if (applicationUser.MemberOrgId != null)
{
ViewBag.SwitchState = true;
}
else
{
ViewBag.SwitchState = false;
}
ViewBag.OrganizationId = new SelectList(db.MemberOrganizations, "Id", "State", applicationUser.MemberOrgId);
// If we got this far, something failed, redisplay form
return View(applicationUser);
}
This enables me to ensure that ONLY 1 of the DropDownList's have a selection made as I clear the current selection when the current DropDownList is hidden via my JavaScript. What I need now is a way to make sure a selection has been made in the currently displayed list before saving the new Identity User to the database.
Now, my Controller correctly identifies when no selection has been made in either list:
if ((applicationUser.MemberOrgId == null) && (applicationUser.SponsorOrgId == null))
{
ModelState.AddModelError("", "Must select either an Organization or Sponsor from the dropdown lists.");
return View(applicationUser);
}
However, when the View is returned, instead of Model State error I am immediately receiving the below at code line #Html.DropDownList("MemberOrgId", ViewData["Organization"] as SelectList, String.Empty, new { #class = "form-control", #id = "MemberOrgId" }):
InvalidOperationException was unhandled by user code.
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'MemberOrgId'.
Anyone have thoughts on how to better handle this?

Related

How can I get textbox value based on Id in another table?

Why doesn't the textbox Name get value by Id?
So this is view ex_op:
This Id and Name, I get based on tbl_operator. When I entered Id then the Name will show.
This is controller ex_op:
public ActionResult Index()
{
var ex_op = db.ex_op.Include(e => e.tbl_exercises).Include(e => e.tbl_operator);
return View(ex_op.ToList());
}
public ActionResult Create()
{
ex_op exop = new ex_op();
var lasttest = db.ex_op.OrderBy(c => c.idTest).FirstOrDefault();
if (lasttest == null)
{
exop.idTest = "EXOP000";
}
else
{
exop.idTest = "EXOP" + (Convert.ToInt32(lasttest.idTest.Substring(6, lasttest.idTest.Length - 6)) + 1).ToString("D3");
}
ViewBag.idEx = new SelectList(db.tbl_exercises, "idEx","idEx");
ViewBag.idOp = new SelectList(db.tbl_operator, "idOp","idOp");
return View(exop);
}
And this is View ex_op
<div class="form-group">
<label class="control-label col-md-2">Name</label>
<div class="control-label col-md-10">
#Html.EditorFor(model => model.tbl_operator.nama, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.tbl_operator.nama, "", new { #class = "text-danger" })
</div>
</div>
I don't know what I forget in this code, maybe i missing the code
please help me.
To auto fill the Name field once a ID Operator is selected you will need to use events to trigger a call to your Controller and return JSON then fill in the Field.
Client Side:
Checks for a change to the operator id dropdown and send a request to the server.
$('#OperatorId').change(function() {
var str = this.options[this.selectedIndex].value;
$.ajax('#Url.Action("GetOperatorName", "Home")', {
type: 'POST',
dataType: 'json',
data : {'operatorId': str }.
success: function(data, status, jqXHR) {
if ("success" === status) {
document.getElementById('#OperatorName').value = data.OperatorName;
} else {
alert('This Operator ID is not valid. Try again!');
}
}
});
});
Server-side:
Receives the ajax request looks up the operator and return the object
public async Task<JsonResult> GetOperatorName(string operatorId)
{
var item = await Operators.Get(x => x.Id == operatorId);
return Json(item);
}
You will need to change the fields and endpoint etc as needed, but this gives you the idea how to achieve what you need.

ASP.NET Identity editing logged in user's data?

I have modified the Views/Manage/Index.cshtml to display the User's email as well. I've modified the IndexViewModel as well so it recognizes the "Email" string and then made another .cshtml page similar to the changing of phone number one which is there by default. The new page is called ChangeEmail.cshtml
#using (Html.BeginForm("ChangeEmail", "Manage", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Add an email</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
From what I've seen, the changing of password happens through a task called "ChangePasswordAsync" inside UserManager.cs
Is there a way to change the Email without making a new task?
EDIT: added more from the controller(index) :
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: message == ManageMessageId.EmailChangedSuccess ? "Your email has been changed"
: "";
var userId = User.Identity.GetUserId();
var userEmail = User.Identity.Name;
var user = UserManager.FindById(userId);
var model = new IndexViewModel
{
HasPassword = HasPassword(),
PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
Logins = await UserManager.GetLoginsAsync(userId),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),
Email = user.Email,
City = user.City,
Region = user.Region
};
user.Email = "topkek#ucn.dk";
UserManager.UpdateAsync(user);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangeEmail(ChangeEmailViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Index", new { Message = ManageMessageId.EmailChangedSuccess });
}
Get the user's Email address from your ChangeEmailViewModel and then update the user's details using the userManager.UpdateAsync(user)
EDIT
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangeEmail(ChangeEmailViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
//Get the user's Id
var userId = User.Identity.GetUserId();
//get the user (you can modify the variables to fit yours)
var user = UserManager.FindByIdAsync(userId);
//this is how to change the Email
user.Result.Email= model.Email// **EDIT**;
userManager.UpdateAync(user.Result);
return RedirectToAction("Index", new { Message = ManageMessageId.EmailChangedSuccess });
}

How to change the value in Html.TextBox for using Jquery and Json?

In the create view what i am trying to do is when you choose a name from the dropdown list to fill the Login html.TextBoxFor automatically with his details.
Currently the Login textbox remains empty when i choose a person from dropdown list.
So i ve got my json object and tested as well my sql which is fine so i suppose the issue must be somewhere in jquery.
I would be glad if you could help me find the error.
View :
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">#Html.LabelFor(model => model.UserLogin)</div>
<div class="editor-field">#Html.TextBoxFor(model => model.UserLogin, new {id ="LoginId" })
#Html.ValidationMessageFor(model => model.UserLogin)</div>
<div class="editor-label">#Html.LabelFor(model => model.UserFullName)</div>
<div class="editor-field">#Html.DropDownList("UserFullName", ViewBag.UserFullName as SelectList, "Select a User", new { id = "UserID" })
#Html.ValidationMessageFor(model => model.UserFullName)</div>
<p>
<input type="submit"
value="Create" />
</p>
</fieldset> }
<div>#Html.ActionLink("Back to List", "Index")</div>
<script type="text/javascript">
$('#UserID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetUserForm")',
data: { FullName: $('#UserID').val() },
success: function (results){
var login = $('#LoginId');
login.empty();
$.each(results, function ()
{
login.val(this.ID).text(this.Value);
});
}});
});
</script>
Controller:
public ActionResult Create()
{
var names = StaffDB.StaffData.AsEnumerable().Select(s => new
{
ID = s.ID,
FullName = string.Format("{0} {1}", s.Forename1, s.Surname)
}).ToList();
if(ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserFullName = new SelectList(names, "FullName", "FullName", user.UserFullName);
return View(user);
}
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new
{
Value = s.Login,
ID = s.ID
};
return Json(data);
}
I think the issue is while returning the json, In MVC by default Jsonresult is "Deny get", so you have add "Allow Get".
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new { Value = s.Login, ID = s.ID };
if (data == null)
return Json(null);
return Json(data , JsonRequestBehavior.AllowGet);
}

Ajax script to Edit records in MVC3 not working

I was doing tutorial from this page here, I was mostly copying
http://ricardocovo.com/2011/04/03/asp-mvc3-editing-records-with-jqueryui-dialogs-and-ajaxforms/
And it is not working and I don't know why. There is no reaction at all.
This is my Edit Method
public ActionResult Edit(int id)
{
ViewBag.Categories = CategoriesSelectList();
return PartialView(proxy.GetProduct(id));
}
This is my Edit View (Partial View). But I dont see any difference from the normal view.
#model Shop.Data.ProductType
<h2>Edit</h2>
#using (Ajax.BeginForm("Edit", "Shop", null,
new AjaxOptions
{
UpdateTargetId = "update-message",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "updateSuccess"
}, new { id = "updateShopForm" }))
{
#Html.ValidationSummary(true)
<div id="update-message" class="error invisible"></div>
<fieldset>
<legend>Products</legend>
#Html.HiddenFor(model => model.CategoryID)
#Html.Label("Nazwa")
<div class="editor-label">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<br />
<br />
#Html.Label("Kategoria")
<div class="editor-label">
#Html.DropDownList("CategoryID", new SelectList(ViewBag.Categories, "value", "text"))
#Html.ValidationMessageFor(model => model.CategoryID)
</div>
</fieldset>
}
And here is this long java from tutorial
<div id="updateDialog" title="Update Product">
</div>
<script type="text/javascript">
var linkObj;
$(function () {
$(".edit-link").button();
$('#updateDialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"Update": function () {
$("#update-message").html(''); //make sure there is nothing on the message before we continue
$("#updateShopForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".edit-link").click(function () {
//change the title of the dialgo
linkObj = $(this);
var dialogDiv = $('#updateDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#updateShopForm");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
});
return false;
});
});
function updateSuccess() {
if ($("#update-message").html() == "True") {
//we update the table's info
var parent = linkObj.closest("tr");
parent.find(".carName").html($("#Name").val());
parent.find(".carDescription").html($("#Description").val());
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").show();
}
}
</script>
And here is my edit link
#Html.ActionLink("Edytuj", "Edit", new { id = m.ID }, new { #class = "edit-link" })
Can't find any difference.

MVC 4 Validation with a partial view

I'm using MVC 4 and Entity Framework to develop a web app. I'm working with partial views which are loaded with javascript. One of them is a create view which includes validation. And that's my problem : the validation. I have a custom validation logic and, for example, if a user enters some numbers into a field such as "Name", it displays an error.
Here, with the partial views, it redirects me on my partial with the errors displayed but what I wanted to do is to stay on my main view (Index view) and keep my partial view which displays the errors.
EDIT :
Here is my partial view :
#model BuSIMaterial.Models.Person
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
First name :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
Last name :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
National number :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.NumNat, new { maxlength = 11 })
#Html.ValidationMessageFor(model => model.NumNat)
</div>
<div class="editor-label">
Start date :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.StartDate, new {#class = "datepicker", #placeholder="yyyy/mm/dd"})
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
End date :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.EndDate, new { #class = "datepicker", #placeholder = "yyyy/mm/dd" })
#Html.ValidationMessageFor(model => model.EndDate)
</div>
<div class="editor-label">
Distance House - Work (km) :
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HouseToWorkKilometers)
#Html.ValidationMessageFor(model => model.HouseToWorkKilometers)
</div>
<div class="editor-label">
Category :
</div>
<div class="editor-field">
#Html.DropDownList("Id_ProductPackageCategory", "Choose one ...")
#Html.ValidationMessageFor(model => model.Id_ProductPackageCategory) Add a new category?
</div>
<div class="editor-label">
Upgrade? :
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Upgrade)
#Html.ValidationMessageFor(model => model.Upgrade)
</div>
<br />
<div class="form-actions">
<button type="submit" class="btn btn-primary">Create</button>
</div>
</fieldset>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/themes/base/css")
}
In my view Index, I have this :
<div class="form-actions"><button type="button" id="create" class="btn btn-primary">Create</button> </div>
<div id ="create_person"></div>
And the way I load my Partial View :
$("#create").click(function () {
var form = $("#create_person").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
$.ajax({
url: "/Person/CreateOrUpdate",
type: "POST",
data: $("#create_person").serialize(),
cache: false
});
// var url = '/Person/CreatePerson';
// $("#create_person").load(url);
});
The actions :
[HttpGet]
public ActionResult CreateOrUpdate()
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name");
return View();
}
[HttpPost]
public JsonResult CreateOrUpdate(Person person)
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
db.Persons.AddObject(person);
db.SaveChanges();
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
If you post the page it will not come back to the dynamically loaded partial view. Try to make a ajax call to /Person/CreatePerson. Your CreatePerson will look similar to
[HttpPost]
public JsonResult CreatePerson(Person person)
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
db.Persons.AddObject(person);
db.SaveChanges();
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
} `
The ajax call to /Person/CreatePerson will look similar to
`
$.ajax({
url: '/Person/CreatePerson',
type: "POST",
data: $("#form").serialize(),
success: function (responce) {
alert(responce.Message);
},
error: function (xhr, textStatus) {
alert(xhr.status + " " + xhr.statusText);
}
});
Besides unobtrusive validation will not work easily with dynamic content. check the link unobtrusive validation on dynamically added partial view (not working)
I've developed a decent workaround for this. The partial page won't show the server errors on postback. First of all, we get the errors, send them back to the page, then create them in javascript & revalidate the page. Hopefully, hey presto!
In your controller:
if (ModelState.IsValid)
{
//... whatever code you need in here
}
var list = ModelStateHelper.AllErrors(ModelState);
TempData["shepherdErrors"] = list;
I put it in TempData so it can be retrieve easily from the partial. Yes, I called it shepherdErrors, it's my idea so I can call the concept whatever silly name I want! Shepherd the error codes to where they should be or something being the general idea.
In a helper class:
public class ModelStateHelper
{
public static IEnumerable<KeyValuePair<string, string>>
AllErrors(ModelStateDictionary modelState)
{
var result = new List<KeyValuePair<string, string>>();
var erroneousFields = modelState.Where(ms => ms.Value.Errors.Any())
.Select(x => new { x.Key, x.Value.Errors });
foreach (var erroneousField in erroneousFields)
{
var fieldKey = erroneousField.Key;
var fieldErrors = erroneousField.Errors
.Select(error => new KeyValuePair<string, string>(fieldKey, error.ErrorMessage)); //Error(fieldKey, error.ErrorMessage));
result.AddRange(fieldErrors);
}
return result;
}
}
Then on the html page somewhere after jquery being loaded:
function displayShepherdErrors() {
var shepherdErrors = JSON.parse('#(Newtonsoft.Json.JsonConvert.SerializeObject(TempData["shepherdErrors"]))'.replace(/"/g, '"'));
var frm;
var isShepherdErrors = (shepherdErrors && shepherdErrors.length > 0);
if (isShepherdErrors) {
errObj = {};
for (var i = 0; i < shepherdErrors.length; i++) {
var errorKey = shepherdErrors[i].Key; //also the id of the field
var errorMsg = shepherdErrors[i].Value;
var reg = new RegExp('^' + errorKey + '$', 'gi');
//find the selector - we use filter so we can find it case insensitive
var control = $('input').filter(function () {
if ($(this).attr('id'))
return $(this).attr('id').match(reg);
});
if (control && control.length) {
control = control[0];
var controlId = $(control).attr('name');
errObj[controlId] = errorMsg;
//get the containing form of the first input element
if (!frm)
frm = control.form;
}
}
var validator = $(frm).validate();
validator.showErrors(errObj);
}
return isShepherdErrors;
}
var isShepherdErrors = displayShepherdErrors();
This should work out of the box with general MVC development provided text boxes that are generated are based on the variable names - this is default behaviour of MVC.

Categories