I have a slight problem here that each time I run the application the first radio button is always checked, I want to make nun of the radio buttons checked. How do I do this?
<div class="col-md-12">
<!--<i class="fa fa-child" aria-hidden="true"></i>-->
#Html.LabelFor(model => model.CCommmunication, "Choose your preferred way of communication", new { #style = "", #class = "", id = "" })
<span style="color: red;">*</span>
#*#Html.DropDownListFor(model => model.Profession, new SelectList(Model.Professions, "Id", "Name"), new { placeholder = "", #style = "", #class = "form-control", id = "Profession" })*#
#Html.EnumRadioButtonFor(model => model.CCommmunication, false,false,"communicationCB") <!--first 2 paramerters are false false communicationCB is the class-->
#Html.ValidationMessageFor(model => model.CCommmunication)
</div>
this is my Model
[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication CCommmunication
{ get; set; }
public enum Commmunication
{
[Display(Name = "Email", Order = 0)]
Email,
[Display(Name = "Mobile telephone", Order = 1)]
TelephoneNo,
[Display(Name = "Alternative telephone", Order = 2)]
TelephoneNoAlternative
}
This is my JavaScript
<script>
var checkedVal = $('.communicationCB input[name=CCommmunication]:checked').val(); //Added a variable to check the value
if (checkedVal == "TelephoneNo") { //if checked valuie
$('.confirmmobtelno').show(); //show this text box
} else {
$('.confirmmobtelno').hide(); //hide textbox
};
if (checkedVal == "TelephoneNoAlternative") { //if checked valuie == to TelephoneNoalternative
$('.confirmalttelno').show(); //show confirm alt tel no text box
} else {
$('.confirmalttelno').hide(); //else hide it
};
$('.communicationCB input[name=CCommmunication]').click(function () { //.communication class passed input name == model public communication
if ($(this).val() == "TelephoneNo") { //if value TelephoneNo selected in model
$('.confirmmobtelno').show(); //show this text box
} else {
$('.confirmmobtelno').hide(); //hide textbox
}
if ($(this).val() == "TelephoneNoAlternative") { //if value == to TelephoneNoalternative
$('.confirmalttelno').show(); //show confirm alt tel no text box
} else {
$('.confirmalttelno').hide(); //else hide it
}
});
Finally I have a enumRadioButton.cs
public static class HtmlHelper
{
public static MvcHtmlString EnumRadioButtonFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
bool includeNoneOption = true,
bool isDisabled = false,
string cssClass = null
) where TModel : class
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
throw new InvalidOperationException("Expression must be a member expression");
var name = ExpressionHelper.GetExpressionText(expression);
var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
ModelState currentValueInModelState;
var couldGetValueFromModelState = htmlHelper.ViewData.ModelState.TryGetValue(fullName, out currentValueInModelState);
object selectedValue = null;
if (couldGetValueFromModelState && htmlHelper.ViewData.Model != null)
{
selectedValue = expression.Compile()(htmlHelper.ViewData.Model);
}
var enumNames = GetSelectItemsForEnum(typeof(TProperty), selectedValue).Where(n => !string.IsNullOrEmpty(n.Value)).ToList();
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
sb.AppendFormat(
"<ul class=\"radio-button-list{0}\">",
string.IsNullOrEmpty(cssClass) ? string.Empty : " " + cssClass);
foreach (var enumName in enumNames)
{
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
enumName.Value
);
if (id.StartsWith("-"))
id = id.Remove(0, 1);
var value = enumName.Value;
sb.AppendFormat(
//"<li>{2} <label for=\"{0}\">{1}</label></li>", //Originol puts data in a list
"{2} <label for=\"{0}\">{1}</label>",
id,
HttpUtility.HtmlEncode(enumName.Text),
isDisabled
? htmlHelper.RadioButtonFor(expression, value, new { id, disabled = "disabled" }).ToHtmlString()
: htmlHelper.RadioButtonFor(expression, value, new { id }).ToHtmlString()
);
}
sb.Append("</ul>");
return MvcHtmlString.Create(sb.ToString());
}
public static IList<SelectListItem> GetSelectItemsForEnum(Type enumType, object selectedValue)
{
var selectItems = new List<SelectListItem>();
if (enumType.IsGenericType &&
enumType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
enumType = enumType.GetGenericArguments()[0];
selectItems.Add(new SelectListItem { Value = string.Empty, Text = string.Empty });
}
var selectedValueName = selectedValue != null ? selectedValue.ToString() : null;
var enumEntryNames = Enum.GetNames(enumType);
var entries = enumEntryNames
.Select(n => new
{
Name = n,
DisplayAttribute = enumType
.GetField(n)
.GetCustomAttributes(typeof(DisplayAttribute), false)
.OfType<DisplayAttribute>()
.SingleOrDefault() ?? new DisplayAttribute()
})
.Select(e => new
{
Value = e.Name,
DisplayName = e.DisplayAttribute.Name ?? e.Name,
Order = e.DisplayAttribute.GetOrder() ?? 50
})
.OrderBy(e => e.Order)
.ThenBy(e => e.DisplayName)
.Select(e => new SelectListItem
{
Value = e.Value,
Text = e.DisplayName,
Selected = e.Value == selectedValueName
});
selectItems.AddRange(entries);
return selectItems;
}
}
}
To have none of the radio buttons selected, you make the property nullable
[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication? CCommmunication { get; set; }
If CCommmunication has an initial value of null, then no radio buttons will be selected.
But its unclear what you trying to do with all that (unnecessary) code in you extension method, in particular why you are creating IList<SelectListItem> (which is for generating a <select> tag). Your helper can simply be
public static class RadioButtonHelper
{
public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
Type type = Nullable.GetUnderlyingType(metaData.ModelType);
if (type == null || !type.IsEnum)
{
throw new ArgumentException(string.Format("The property {0} is not an enum", name));
}
StringBuilder html = new StringBuilder();
foreach (Enum item in Enum.GetValues(type))
{
string id = string.Format("{0}_{1}", metaData.PropertyName, item);
StringBuilder innerHtml = new StringBuilder();
innerHtml.Append(helper.RadioButtonFor(expression, item, new { id = id }));
innerHtml.Append(helper.Label(id, item.ToDescription()));
TagBuilder div = new TagBuilder("div");
div.AddCssClass("radiobutton");
div.InnerHtml = innerHtml.ToString();
html.Append(div.ToString());
}
TagBuilder container = new TagBuilder("div");
container.AddCssClass("radiobutton-container");
container.InnerHtml = html.ToString();
return MvcHtmlString.Create(container.ToString());
}
}
which uses the following extension method
public static class EnumExtensions
{
public static string ToDescription(this Enum value)
{
if (value == null)
{
return null;
}
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
return value.ToString();
}
}
in association with the [Description] attribute applied to your enum values rather that the [Display] attribute (but you can easily modify that)
Related
I found out that my index page wasn't showing the updated user info for currently logged in user. So I changed the form page from:
<div class="col-xs-4">
<div class="col-md-4">
#Html.HiddenFor(model => model.SubmittedDate, new { Value = System.DateTime.Now })
#Html.HiddenFor(model => model.SubmittedBy, new { Value = Model.ADAccount })
</div>
</div>
**to:**
<div class="col-xs-4">
<div class="col-md-4">
#Html.HiddenFor(model => model.SubmittedDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.SubmittedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.UpdatedDate, new { Value = System.DateTime.Now })
#Html.HiddenFor(model => model.UpdateBy, new { htmlAttributes = new { Value = Model.ADAccount } })
</div>
</div>
I had also tried changing the form page like this but it didn't change anything:
#Html.HiddenFor(model => model.UpdateBy, new { Value = Model.ADAccount })
The submit looks like this in the form page:
#(Html.Kendo().Button()
.Name("submit")
.Content("Submit")
.HtmlAttributes(new { #class = "k-primary" })
.Events(ev => ev.Click("onClick")))
But for some reason it's still not showing the UpdateBy in the Index list. I don't see a specific reference in the Controller for UpdateBy or SubmittedBy. I see them both in the ApplicantCapturedData.cs list:
public string UpdateBy { get; set; }
public string SubmittedBy { get; set; }
I see in ApplicantController.cs, the Edit Post puts some data in the DB, but doesn't mention the updateBy or SubmittedBy variables or model specifically. However, in the old code, the SubmittedBy variable change did show on the index list. I looked in the project, and there are no specific references to SubmittedBy besides ApplicantController
When I put a watch on UpdateBy, I see it go back and forth between the old user, me, and null. Apparently it ends with the old user, because that's what is displayed in the list of applicants on the index after the form is submitted.
Any thoughts on how to fix this? I'm new to MVC, and I'm not sure why this change isn't getting back to the model/db. When the applicantController gets the applicantCapturedData, it shows the old value for UpdateBy, not the new value.
The Edit Method should return current loged-in user to the view instead of BD data, but it's not. I'm not sure why.
I looked at controller not receiving model info, but it didn't seem like the same issue to me.
Let me know if you think I'm leaving any crucial info out that you need. I obviously can't post all of the mvc files and code here for clarity and sanity.
******Update*********
This is the Edit/Post method in ApplicantController.cs. It doesn't specifically refer to the SubmittedBy or UpdateBy, but the SubmittedBy part does show up in the index, even when we updated it in the form with current AD user:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ApplicantCapturedData applicantCapturedData)
{
var eRecordSchedulinglist = applicantCapturedData.ERecordScheduling;
var eRecordScheduling = new ERecordScheduling();
// int IDs = applicantCapturedData.ID;
//updating Provider License
var providerLicenselist = applicantCapturedData.ProviderLicense;
var providerLicense = new ProviderLicense();
var eprescribelist = applicantCapturedData.EPrescribe;
var eprescribe = new EPrescribe();
//updating payor table
var payorlist = applicantCapturedData.Payor;
var payor = new Payor();
//updating tax table
var taxlist = applicantCapturedData.TaxNPITaxonomy;
var tax = new TaxNPITaxonomy();
if (ModelState.IsValid)
{
//ERecordScheduling eRecordScheduling = new ERecordScheduling();
db.Entry(applicantCapturedData).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
int getid = applicantCapturedData.ID;
//Getting values for provider license already in db
var query = from p in db.ProviderLicenses
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in query)
{
db.ProviderLicenses.Remove(i);
}
db.SaveChanges();
int c = 1;
if (providerLicenselist != null)
{
var updatePLS = providerLicenselist.ToList();
// adding only new record to db
foreach (var i in updatePLS)
{
providerLicense.LicenseNumber = i.LicenseNumber;
providerLicense.State = i.State;
providerLicense.ProviderLicenseID = i.ProviderLicenseID;
i.ApplicantCapturedData_ID = getid;
if (providerLicense.ProviderLicenseID <= c)
{
providerLicense.ProviderLicenseID = providerLicense.ProviderLicenseID++;
}
db.ProviderLicenses.Add(i);
db.SaveChanges();
}
}
//getting Values already existing in db for Erecording Schedulign
var queryERS = from p in db.ERecordSchedulings
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in queryERS)
{
db.ERecordSchedulings.Remove(i);
}
db.SaveChanges();
if (eRecordSchedulinglist != null)
{
var updateESCH = eRecordSchedulinglist.ToList();
foreach (var item in updateESCH)
{
eRecordScheduling.DepartmentName = item.DepartmentName;
eRecordScheduling.Shedules = item.Shedules;
eRecordScheduling.VisitType = item.VisitType;
eRecordScheduling.GenericProvider = item.GenericProvider;
eRecordScheduling.ERecordSchedulingID = item.ERecordSchedulingID;
// a.ApplicantCapturedData_ID = newid;
item.ApplicantCapturedData_ID = getid;
if (eRecordScheduling.ERecordSchedulingID <= c)
{
eRecordScheduling.ERecordSchedulingID = eRecordScheduling.ERecordSchedulingID++;
}
//save to db
db.ERecordSchedulings.Add(item);
db.SaveChanges();
}
}
//Getting Values that already exisit in db for Taxonomy
var querytaxo = from p in db.TaxNPITaxonomies
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in querytaxo)
{
db.TaxNPITaxonomies.Remove(i);
}
db.SaveChanges();
if (taxlist != null)
{
var UpdateTaxo = taxlist.ToList();
foreach (var t in UpdateTaxo)
{
tax.GroupNPI = t.GroupNPI;
tax.Notes = t.Notes;
tax.TaxID = t.TaxID;
tax.TaxNPITaxonomyID = t.TaxNPITaxonomyID;
tax.Taxonomy = t.TaxID;
t.ApplicantCapturedData_ID = getid;
if (tax.TaxNPITaxonomyID <= c)
{
tax.TaxNPITaxonomyID = tax.TaxNPITaxonomyID++;
}
db.TaxNPITaxonomies.Add(t);
db.SaveChanges();
}
}
var queryeprescribe = from p in db.EPrescribes
where p.ApplicantCapturedData_ID == getid
select p;
foreach (var i in queryeprescribe)
{
db.EPrescribes.Remove(i);
}
db.SaveChanges();
if (eprescribelist != null)
{
var updateeprescribe = eprescribelist.ToList();
foreach (var t in updateeprescribe)
{
eprescribe.EPrescribeOptions = t.EPrescribeOptions;
eprescribe.ID = t.ID;
t.ApplicantCapturedData_ID = getid;
if (eprescribe.ApplicantCapturedData_ID <= c)
{
eprescribe.ApplicantCapturedData_ID = eprescribe.ApplicantCapturedData_ID++;
}
db.EPrescribes.Add(t);
db.SaveChanges();
}
}
//Geting values that already exist in db for Payors
var queryPayor = from p in db.Payors
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in queryPayor)
{
db.Payors.Remove(i);
}
db.SaveChanges();
if (payorlist != null)
{
var updatepayor = payorlist.ToList();
foreach (var p in updatepayor)
{
payor.Pyor = p.Pyor;
payor.PayorID = p.PayorID;
p.ApplicantCapturedData_ID = getid;
if (payor.PayorID <= c)
{
payor.PayorID = payor.PayorID++;
}
db.Payors.Add(p);
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
return View(applicantCapturedData);
}
Here's the save in ApplicantController.cs. It doesn't have a specific reference to UpdateBy or SubmittedBy either, and yet SubmittedBy used to update when I changed the AD user:
// [HttpPost]
public ActionResult Save(ApplicantCapturedData applicantCapturedData)
{
ViewBag.PostedBills = applicantCapturedData.BillingAreas;
applicantCapturedData.BillingAreas = applicantCapturedData.BillingAreas;
//updating eRecordScheduling
var list = applicantCapturedData.ERecordScheduling;
var a = new ERecordScheduling();
var OtherAddressList = applicantCapturedData.PracticeInfoOtherLocations;
var otheraddresses = new PracticeInfoOtherLocation();
//var payorlist = applicantCapturedData.Payor;
//var payor = new Payor();
// int IDs = applicantCapturedData.ID;
//updating Provider License
var providerLicenselist = applicantCapturedData.ProviderLicense;
var providerLicense = new ProviderLicense();
var Eprescribelist = applicantCapturedData.EPrescribe;
var eprescribe = new EPrescribe();
//updating payor table
var payorlist = applicantCapturedData.Payor;
var payor = new Payor();
//updating tax table
var taxlist = applicantCapturedData.TaxNPITaxonomy;
var tax = new TaxNPITaxonomy();
// var lastEnt = db.ERecordSchedulings.AsEnumerable().Where(i => i.ERecordSchedulingID.CompareTo(a.ERecordSchedulingID))
int c = 1;//lastEnter.LastOrDefault().ERecordSchedulingID;
if (ModelState.IsValid)
{
db.ApplicantCapturedDatas.Add(applicantCapturedData);
// db.ERecordSchedulings.Add(applicantCapturedData);
db.SaveChanges();
//db.ERecordSchedulings.Add(applicantCapturedData.ERecordScheduling);
//get the primary key id after adding to the Db
int newid = applicantCapturedData.ID;
if (applicantCapturedData.ERecordScheduling != null)
{
// check if we have more record on Erecord scheduling using the count
//if count is greater than zero we have record to add to db.
if (applicantCapturedData.ERecordScheduling.Count() > 0)
{
/*
* This loops thru the list and add record
*
*/
foreach (var item in list)
{
a.DepartmentName = item.DepartmentName;
a.Shedules = item.Shedules;
a.VisitType = item.VisitType;
a.GenericProvider = item.GenericProvider;
a.ERecordSchedulingID = item.ERecordSchedulingID;
// a.ApplicantCapturedData_ID = newid;
item.ApplicantCapturedData_ID = newid;
//if you put a breakpoint at the beginning of this class you will see that all id is 0 I had to increment the id so I don't override itself.
if (a.ERecordSchedulingID <= c)
{
a.ERecordSchedulingID = a.ERecordSchedulingID++;
}
//save to db
db.ERecordSchedulings.Add(item);
db.SaveChanges();
//item.LicenseNumber = a.LicenseNumber;
//item.State = a.State;
//item.ProviderLicenseID = a.ProviderLicenseID;
}
}
}
if (applicantCapturedData.ProviderLicense != null)
{
if (applicantCapturedData.ProviderLicense.Count() > 0)
{
foreach (var i in providerLicenselist)
{
providerLicense.LicenseNumber = i.LicenseNumber;
providerLicense.State = i.State;
providerLicense.ProviderLicenseID = i.ProviderLicenseID;
i.ApplicantCapturedData_ID = newid;
if (providerLicense.ProviderLicenseID <= c)
{
providerLicense.ProviderLicenseID = providerLicense.ProviderLicenseID++;
}
db.ProviderLicenses.Add(i);
db.SaveChanges();
}
}
}
if (applicantCapturedData.Payor != null)
{
if (applicantCapturedData.Payor.Count() > 0)
{
foreach (var p in payorlist)
{
payor.Pyor = p.Pyor;
payor.PayorID = p.PayorID;
p.ApplicantCapturedData_ID = newid;
if (payor.PayorID <= c)
{
payor.PayorID = payor.PayorID++;
}
db.Payors.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.PracticeInfoOtherLocations != null)
{
if (applicantCapturedData.PracticeInfoOtherLocations.Count() > 0)
{
foreach (var p in OtherAddressList)
{
otheraddresses.City = p.City;
otheraddresses.Fax = p.Fax;
otheraddresses.Phone = p.Phone;
otheraddresses.State = p.State;
otheraddresses.Street = p.Street;
otheraddresses.Suite = p.Suite;
otheraddresses.ZipCode = p.ZipCode;
otheraddresses.AppID = newid;
otheraddresses.ID = p.ID;
if (otheraddresses.ID <= c)
{
otheraddresses.ID = otheraddresses.ID++;
}
db.PracticeInfoOtherLocations.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.EPrescribe != null)
{
if (applicantCapturedData.EPrescribe.Count() > 0)
{
foreach (var p in Eprescribelist)
{
eprescribe.EPrescribeOptions = p.EPrescribeOptions;
eprescribe.ID = p.ID;
p.ApplicantCapturedData_ID = newid;
if (eprescribe.ID <= c)
{
eprescribe.ID = eprescribe.ID++;
}
db.EPrescribes.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.TaxNPITaxonomy != null)
{
if (applicantCapturedData.TaxNPITaxonomy.Count() > 0)
{
foreach (var t in taxlist)
{
tax.GroupNPI = t.GroupNPI;
tax.Notes = t.Notes;
tax.TaxID = t.TaxID;
tax.TaxNPITaxonomyID = t.TaxNPITaxonomyID;
tax.Taxonomy = t.TaxID;
t.ApplicantCapturedData_ID = newid;
if (tax.TaxNPITaxonomyID <= c)
{
tax.TaxNPITaxonomyID = tax.TaxNPITaxonomyID++;
}
db.TaxNPITaxonomies.Add(t);
db.SaveChanges();
}
}
}
return RedirectToAction("Index");
}
return View(applicantCapturedData);
}
I would like to count the words in the text area instead of each individual character.
Model Class
[RegularExpression(#"[^<>]*", ErrorMessage = "Invalid entry"), StringLength(200)]
public string Day1Journal { get; set; }
HTML
#Html.TextAreaFor(m => m.StudentJournaldtls.Day1Journal, IsReadOnly == true || IsSubmitted == true ? (object)new { col = 2, #class = "CharacterLimit required", #maxlength = 200, #readonly = "readonly" } : new { col = 2, #class = "CharacterLimit required", #maxlength = 200 })
<small>No of characters left:<span class="charsLeft"></span></small>
Javascript
<script type="text/javascript">
$(function () {
$(".CharacterLimit").each(function (i, t) {
var charsLeft = $(this).attr("maxlength") - $(this).val().split(' ').length
$(this).parent().find(".charsLeft").text(charsLeft);
});
$(".CharacterLimit").keyup(function (e) {
var charsLeft = $(this).attr("maxlength") - $(this).val().split(' ').length
$(this).parent().find(".charsLeft").text(charsLeft);
});
</script>
you can get the words count in the text by spliting the value by white spaces, like:
$("textbox").val().split(' ').length
Hi I need to add items to list, it works when the list have elements but when list is empty javascript return undefined.
this is my function: namevalue is undefined when list is empty I think its main problem.
function submitAjaxForm(formId)
{
var form = $("<form></form>");
var targetID = formId.substr(1);
form.append($(formId).html());
var nameValue = $(formId).find('.showDictionariesList').first().find('input[type="hidden"]').first().attr('name');
var indexToCut = nameValue.indexOf('[', nameValue.indexOf('[', 0) + 1);
var featureIndex = nameValue.substring(0, indexToCut);
var contentVal = $("#dropDownList option:selected").val();
var returnValue = form.serializeArray();
returnValue[returnValue.length - 1].value = contentVal;
}
This list
public List<ShowDictionaryModel> ShowDictionaries { get; set; }
class of this items:
public class ShowDictionaryModel
{
public long Id { get; set; }
public string Value { get; set; }
public long? ProductId { get; set; }
public string FeatureId { get; set; }
internal static ShowDictionaryModel FromDto(DictionaryDto dto)
{
ShowDictionaryModel model = new ShowDictionaryModel();
model.Id = dto.Id;
model.Value = dto.Value;
model.ProductId = dto.ProductId;
model.FeatureId = dto.FeatureId;
return model;
}
}
Cshtml code: showDictionariesList is class who contains the list what i want to modify
#model MultiShop.Panel.Models.Product.AddProductFeatureTextModel
<div>
<div id="featureText-#Model.TypeId">
#Html.HiddenFor(m => m.TypeId)
#Html.HiddenFor(m => m.IsRequired)
#Html.HiddenFor(m => m.Name)
#Html.Label(Model.Name)
#Html.TextBoxFor(m => m.Value)
#if (Model.IsRequired)
{
<span class="requiredField"></span>
}
#Html.ValidationMessageFor(m => m.Value)
<div class="showDictionariesList">
#Html.EditorFor(m => m.ShowDictionaries)
</div>
#Html.DropDownListFor(m => m.SelectedDictionaryItemId, new SelectList(Model.DictionaryItems, "Id", "Value", Model.SelectedDictionaryItemId), new { id = "dropDownList" })
<input type="button" value="Save" onclick="#("submitAjaxForm('#featureText-" + #Model.TypeId + "')")" />
</div>
//}
your problem that youre trying to get attribute on non existing object
you should get it after check
var container = $(formId).find('.showDictionariesList').first();
var nameValueObj = container.find('input[type="hidden"]').first();
if (nameValueObj.length !== 0){
// input was found so we can get name attribute
var nameValue= nameValueObj.attr('name');
var indexToCut = nameValue.indexOf('[', nameValue.indexOf('[', 0) + 1);
// .........
} else{
// as far no input elements inside .showDictionariesList your logic to add first one item
// container.append(
}
I got answer for it. I just initialize list with basic element if is null. My experience with programming is very low so my code look bad but it works as I want.
if (!dictionaryType.HasItems())
{
DictionaryDto newForEmptyList = new DictionaryDto();
List<DictionaryDto> newList = new List<DictionaryDto>();
newForEmptyList.FeatureId = type;
newForEmptyList.ProductId = productId;
newForEmptyList.Value = "";
newForEmptyList.Id = -1;
newList.Add(newForEmptyList);
dictionaryType = newList.ToArray();
}
I've been trying to get some custom client site date validation working and so far I cannot seem to get it to work properly.
I have a custom date editor defined like this:
#model DateTime?
#{
if (Model.HasValue)
{
int day = Model.Value.Day;
int month = Model.Value.Month;
int year = Model.Value.Year;
}
List<SelectListItem> days = new List<SelectListItem>();
for (int i = 1; i <= 31; i++)
{
days.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Day == i});
}
List<SelectListItem> months = new List<SelectListItem>();
for (int i = 1; i <= 12; i++)
{
months.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Month == i});
}
List<SelectListItem> years = new List<SelectListItem>();
var minYear = DateTime.Now.Year - 100;
var maxYear = DateTime.Now.Year - 18;
for (int i = maxYear; i >= minYear; i--)
{
years.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Year == i });
}
}
#Html.DropDownList("days", days, "Day", new { #class="form__select" } )
#Html.DropDownList("months", months, "Month", new { #class="form__select" } )
#Html.DropDownList("years", years, "Year", new { #class="form__select" } )
And I have a custom validation attribute defined like this:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class DoBValidatorAttribute : ValidationAttribute, IClientValidatable
{
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
List<ModelClientValidationRule> clientRules = new List<ModelClientValidationRule>();
ModelClientValidationRule validDateRule = new ModelClientValidationRule
{
ErrorMessage = "Please enter a valid date.",
ValidationType = "validdate"
};
validDateRule.ValidationParameters.Add("dayelement", metadata.PropertyName + ".days");
validDateRule.ValidationParameters.Add("monthelement", metadata.PropertyName + ".months");
validDateRule.ValidationParameters.Add("yearelement", metadata.PropertyName + ".years");
clientRules.Add(validDateRule);
return clientRules;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime dateResult;
int day = Convert.ToInt32(validationContext.Items["days"]);
int month = Convert.ToInt32(validationContext.Items["months"]);
int year = Convert.ToInt32(validationContext.Items["years"]);
// Put date parts together and check is valid...
if (DateTime.TryParse(year + "/" + month + "/" + day, out dateResult))
{
return ValidationResult.Success;
}
// Not valid
return new ValidationResult(string.Format(ErrorMessageString, validationContext.DisplayName));
}
}
In order to (try) and wire all this together I also have this in my JavaScript:
jQuery.validator.unobtrusive.adapters.add(
'validdate', // notice this is coming from how you named your validation rule
['dayelement'],
['monthelement'],
['yearelement'],
function (options) {
options.rules['datepartcheck'] = options.params;
options.messages['datepartcheck'] = options.message;
}
);
jQuery.validator.addMethod('datepartcheck', function (value, element, params) {
var year = params[2];
var month = params[1];
var day = params[0];
var birthDate = year + '/' + month-1 + '/' + day;
var isValid = true;
try {
// datepicker is a part of jqueryUI.
// include it and you can take advantage of .parseDate:
$.datepicker.parseDate('yy/mm/dd', birthDate);
}
catch (error) {
isValid = false;
}
return isValid;
}, '');
I've put a breakpoint on all these methods but the GetClientValidationRules method is never called which I think means that the rules are never going to be applied to the HTML for one thing.
What am I doing wrong here? I just cannot figure it out. If I could I would ditch all of it and use a plain datepicker but the client is insistent on this format.
UPDATE
Just to be clear in the generated HTML the controls generated are three <select> inputs.
I'm wondering if it might be better to split this into three separate int properties on my model and use a range validator instead.
I am working in ASP.NET project. And my task is to append the Checkbox text to the TextBox. Checkboxes's text are bound from Database values in CheckBoxList.
protected void prbtn_Click(object sender, EventArgs e)
{
string ConnectionString = "Data Source=.;Initial Catalog=nci;Integrated Security=true";
SqlConnection myConn = new SqlConnection(ConnectionString);
List<string> minire = new List<string>();
string sql = "SELECT distinct PRIMARY_MINI_REGION FROM customers";
myConn.Open();
SqlCommand cmd = new SqlCommand(sql, myConn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
minire.Add(dt.Rows[0][0].ToString());
group12.DataSource = dt;
group12.DataTextField = "PRIMARY_MINI_REGION";
group12.DataValueField = "PRIMARY_MINI_REGION";
group12.DataBind();
string[] grpary = prgrp.Text.Split(';');
foreach (var items in grpary)
{
if (items != "")
{
li.Add(items.ToString());
if (li.Contains(items.ToString()))
{
group12.Items.FindByText(items.ToString()).Selected = true;
//group12.Items.FindByText(items.ToString()).Enabled = false;
}
}
}
}
Can any of you please help me how to do it in jquery.Currently i appended text using stringbuilder using C# as like
protected void group_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem l in group12.Items)
{
if (l.Selected)
{
li.Add(l.Text);
}
}
foreach (var i in li)
{
si.Append(i.ToString() + ";");
}
//if (prgrp.Text == "")
// prgrp.Text = si.ToString();
//else
prgrp.Text = si.ToString();
}
once i select checkbox means it have to append text.and once i unchecked it means,content have to be deleted from textbox
I guess this snippet helps you out:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// Repeat for all checked checkboxes:
$('input[type="checkbox"]:checked').each(function(){
// Get values:
var existingText = $("#output").html();
var textToAppend = $(this).val();
// Append seperator (';') if neccessary:
if(existingText != '')
{
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan"/>Jan
<input type="checkbox" value="Feb"/>Feb
<input type="checkbox" value="Mar"/>Mar
<input type="checkbox" value="Apr"/>Apr
<h2>Output:</h2>
<div id="output"></div>
$(document).ready(
$('.checkBoxCommunClass').on('click', function () {
var id = $(this).get(0).id;
if ($('input[id=' + id + ']:checked').length > 0)
$('#resultTextInput').val() = $('#resultTextInput').val() + $(this).val();
}));