Kendo Editors not working in jQuery Steps? - asp.net

I am using jQuery steps within a form.
I have some model properties which I want to edit using Kendo Editors.
I a using following (partial) code, the rest is markup for the jQuery wizard:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Start, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Start, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Start, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.End, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.End, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.End, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#(Html.Kendo().DropDownListFor(x => x.RecurrenceRule)
.Name("recurrenceRule")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>
{
new SelectListItem
{
Text = #"Nie",
Value = "Never"
},
new SelectListItem
{
Text = #"Täglich",
Value ="Daily"
},
new SelectListItem
{
Text = #"Monatlich",
Value ="monthly"
}
}))
</div>
</div>
}
For some reason, the editors for Date properties are not properly displayed while the #(Html.Kendo().DropDownListFor( is working just fine.
In another step (not documented here) #(Html.Kendo().MultiselectFor( does not work correctly either.
What could cause this issue?
Update:
Positioning this code outside the markup for jQuery steps works fine. Here is my code for the wizard:
#using (Ajax.BeginForm("Wizard_Submit", "Wizard", new
{
Area = ""
}, new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace
}, new
{
id = "wizardSumbit"
}))
{
////0
<div id="wizard">
<h3></h3>
<section>
<p></p>
#(Html.Kendo().DropDownListFor(x => x.SlRateBaseTypes)
.Name("slRateBaseTypes")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>
{
new SelectListItem
{
Text = #"abc",
Value = ((int) SlRateBaseTypes.Course).ToString()
},
new SelectListItem
{
Text = #"cde",
Value = ((int) SlRateBaseTypes.Leisure).ToString()
}
}))
</section>
#*//1*#
<h3>Vorlage</h3>
<section>
<p>Wähle eine Vorlage aus</p>
#(Html.Kendo().DropDownListFor(x => x.OfferingTemplateId)
.Name("offeringTemplate")
.DataTextField("Text")
.DataValueField("Value")
.Events(x => x.Change("onOfferingTemplateChange"))
.DataSource(
source => source
.Read(read => read.Url(Url.Action("Wizard_GetOfferingTemplates", "Wizard")).Data("getSlRateBaseTypesSelection").Type(HttpVerbs.Post))
.ServerFiltering(true)
)
.AutoBind(false))
<div id="offeringTemplateDescription"></div>
</section>
#*//2*#
<h3></h3>
<section>
<p></p>
<label for="optional"></label>
#(Html.Kendo().MultiSelectFor(x => x.SlRateBaseTypes)
.Name("selectOfferingRateTypes")
.Placeholder("")
.AutoClose(false)
.DataTextField("Text")
.DataValueField("Value")
.DataSource(
source => source
.Read(read => read.Url(Url.Action("Wizard_GetPossibleOfferingRates", "Wizard")).Data("getSlRateBaseTypesSelection").Type(HttpVerbs.Post))
.ServerFiltering(true)
)
)
..
}
Developer options reveal following :
"Cannot read property 'inspectKendoWidget' of undefined"
"TypeError: Cannot read property 'inspectKendoWidget' of undefined
at :1:15"
Update 2:
this is the html code for the documented datepicker:
<span class="k-widget k-datetimepicker k-header k-input" style="width: 100%;">
<span class="k-picker-wrap k-state-default"><input data-val="true" data-val-date="The field Start must be a date." data-val-required="The Start field is required." id="Start" name="Start" type="text" value="01.01.0001 00:00" data-role="datetimepicker" class="k-input" role="combobox" aria-expanded="false" aria-disabled="false" style="width: 100%;" vk_15f93="subscribed">
<span unselectable="on" class="k-select">
<span class="k-link k-link-date" aria-label="Open the date view">
<span unselectable="on" class="k-icon k-i-calendar" aria-controls="Start_dateview"><
/span>
</span>
<span class="k-link k-link-time" aria-label="Open the time view">
<span unselectable="on" class="k-icon k-i-clock" aria-controls="Start_timeview">
</span>
</span>
</span>
</span>
</span>

Just in case anybody cares:
you'll have to remove some css styles in the jQuery steps css file
-> change to:
.tabcontrol ul > li
{
display: block;
/*padding: 0;*/
}
Update:
Also important: Actually the basic problem was solved by modifiying the jquery.steps.js file according to another post I found on the internet:
--> comment this section
//function render(wizard, options, state)
//{
// // Create a content wrapper and copy HTML from the intial wizard structure
// var wrapperTemplate = "<{0} class=\"{1}\">{2}</{0}>",
// orientation = getValidEnumValue(stepsOrientation, options.stepsOrientation),
// verticalCssClass = (orientation === stepsOrientation.vertical) ? " vertical" : "",
// contentWrapper = $(wrapperTemplate.format(options.contentContainerTag, "content " + options.clearFixCssClass, wizard.html())),
// stepsWrapper = $(wrapperTemplate.format(options.stepsContainerTag, "steps " + options.clearFixCssClass, "<ul role=\"tablist\"></ul>")),
// stepTitles = contentWrapper.children(options.headerTag),
// stepContents = contentWrapper.children(options.bodyTag);
// // Transform the wizard wrapper and remove the inner HTML
// wizard.attr("role", "application").empty().append(stepsWrapper).append(contentWrapper)
// .addClass(options.cssClass + " " + options.clearFixCssClass + verticalCssClass);
// // Add WIA-ARIA support
// stepContents.each(function (index)
// {
// renderBody(wizard, state, $(this), index);
// });
// stepTitles.each(function (index)
// {
// renderTitle(wizard, options, state, $(this), index);
// });
// refreshStepNavigation(wizard, options, state);
// renderPagination(wizard, options, state);
// }
-->replace with this
function render(wizard, options, state) {
// Create a content wrapper and copy HTML from the intial wizard structure
var contentWrapperTemplate = "<{0} class=\"{1}\"></{0}>",
stepsWrapperTemplate = "<{0} class=\"{1}\">{2}</{0}>",
orientation = getValidEnumValue(stepsOrientation, options.stepsOrientation),
verticalCssClass = (orientation === stepsOrientation.vertical) ? " vertical" : "",
contentWrapper = $(contentWrapperTemplate.format(options.contentContainerTag, "content " + options.clearFixCssClass)),
stepsWrapper = $(stepsWrapperTemplate.format(options.stepsContainerTag, "steps " + options.clearFixCssClass, "<ul role=\"tablist\"></ul>"));
// Transform the wizard wrapper by wrapping the innerHTML in the content wrapper, then prepending the stepsWrapper
wizard.attr("role", "application").wrapInner(contentWrapper).prepend(stepsWrapper)
.addClass(options.cssClass + " " + options.clearFixCssClass + verticalCssClass);
//Now that wizard is tansformed, select the the title and contents elements
var populatedContent = wizard.find('.content'),
stepTitles = populatedContent.children(options.headerTag),
stepContents = populatedContent.children(options.bodyTag);

Related

ASP.NET MVC Dropdown Default value

Please look at my code. I am trying to load the default value for the drop-down. value is not accepting from the design. I'm loading data to the combobox from, the account controller, I have added list of items to the Tempdata and then in the design I'm assigning the list to the combo box. So here when loading the form I need to set the default value for the combo box drop down list. Please help
This is how I assigning values from the account controller.
List<Request_Types> RequestTyleList = db.Request_Types.Where(r => r.Status == true).ToList();
List<SelectListItem> ReqTypeDropDown = RequestTyleList.Select(r => new SelectListItem { Text = r.Request_Type, Value = r.Id.ToString() }).ToList();
TempData["RequestTyleList"] = ReqTypeDropDown;
This how I called that TempData in the view:
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
}
And this is where I assigning that values to the Combobox in the view
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.ReqType, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.ReqType, ReqTypes, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.ReqType, "", new { #class = "text-danger" })
</div>
</div>
</div>
So I when opening the view, I need to assign the default value to the ReqTypes
Just add the following parameter to assign default value
#Html.DropDownListFor(model => model.ReqType, new SelectList(ReqTypes,"Value","Text","Your_Default_Value"), "Select",new { #class = "js-dropdown" })

Bootstrap "required" class not working for current MVC web app

I'm currently working with an MVC web app. I went in to restyle the Create template and after doing so, I lost the ability to mark required fields with a red asterisk. I don't understand why my code is no longer working. Please help. Code below:
HTML/Razor Syntax
<div class="form-group required col-md-4">
#Html.LabelFor(model => model.Buy1FirstName)
#Html.EditorFor(model => model.Buy1FirstName, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Buy1FirstName, "Please enter a valid first name", new { #class = "text-danger" })
</div>
My CSS/StyleSheet
.form-group .required .control-label:after {
content:" *" !important;
color:red !important;
}
This is what it currently looks like. It should have a red * after the label "First Name".
I believe that there are two small errors here.
The control-label class reference is in your css, but not in the actual html tag.
The css selectors are a little off just as the comments mention. I just tried your code and was able to see the red asterisk with
these changes:
<div class="form-group required col-md-4">
#Html.LabelFor(model => model.Buy1FirstName, new { #class = "control-label" })
#Html.EditorFor(model => model.Buy1FirstName, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Buy1FirstName, "Please enter a valid first name", new { #class = "text-danger" })
.form-group.required .control-label:after {
content: " *" !important;
color: red !important;
}
Notice the only thing I changed was adding the class reference in the html label to "control-label", and removing the space between .form-group and .required in the css section.

Required Validation Not working For DropdownList in MVC

Below View Code. when i click on Create button without Selecting Activity. it is not showing validation message. i am using Required attribute in Model Class
<div class="form-group">
#Html.LabelFor(model => model.TransactionTypeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TransactionTypeID, new SelectList(ViewBag.GetT, "TransactionTypeID", "TransactionType"), "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TransactionTypeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ActivityID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ActivityID, new SelectList(ViewBag.GetA, "ActivityID", "ActivityName"), "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActivityID, "", new { #class = "text-danger" })
</div>
</div>
//Controller code
public ActionResult Create()
{
List<TransactionTypeMaster> T = new DATransactionTypeMaster().GetListAll();
ViewBag.GetT = T;
List<ActivityMaster> A = new DAActivityMaster().GetListAll();
ViewBag.GetA = A;
return View();
}
Can Any One Help on this. Need To Know Where i m going Wrong
when i click on Create button without Selecting Activity. it is not showing validation message. i am using Required attribute in Model Class
try giving the default '--Select--' options in your drop downs a value of 0.
In your model, make sure your drop down value is set to '[Required]' and also give it the attribute:
[Range(1, Int32.MaxValue, ErrorMessage = "Must Select A Value")]
basically letting it only accept values > 0
I think you TransactionTypeID is int, make that Nullable that would fix this issue. Currently it doesn't work because by default it might be sending zero as a value by using null, it would send null when user doesn't touch this field.

ASP MVC Razor - FormValidation - #Html.ValidationMessageFor - Editor [duplicate]

This question already has an answer here:
attaching jquery validation to replacement element
(1 answer)
Closed 6 years ago.
Validation working on all other elements i used sofar but validation-message for editor does not show up. ModelState has correct error-state,
but no message can be seen on the form.
here is what i have:
MODEL:
[Required(AllowEmptyStrings = false, ErrorMessage = "Diese Feld muss angegeben werden.")]
[StringLength(8000,ErrorMessage = "Feld muss zwischen {2} und {1} Zeichen enthalten.", MinimumLength = 8)]
[DataType(DataType.MultilineText)]
[AllowHtml]
[Display(Name = "Beschreibung")]
public string Description { get; set; }
VIEW:
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
this also does not work:
#Html.ValidationMessageFor(model => model.Description)
when i do this in view:
#Html.ValidationMessageFor(model => model.Description, "test message")
it works - meaning, it shows "test message" - but i want the messages i defined in model...
---- here is some field that works as expected ----
MODEL:
[Required(ErrorMessage = "Dieses Feld muss angegeben werden.")]
[StringLength(25, MinimumLength = 2)]
[Display(Name = "KeyWord")]
public string Keyword { get; set; }
VIEW:
<div class="form-group">
#Html.LabelFor(model => model.Keyword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Keyword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Keyword, "", new { #class = "text-danger" })
</div>
</div>
when field is empty and submit attempted, the required message is shown.
when field contains too-less or too many characters, and field is not in focus or submit is attempted, string-length message is shown ..
that's what i would like for the 2nd editor ...
----- end of working field -----
what am i doing wrong ?
thank you
SOLVED:
it was that "jQuery TE" was used to beautify the editor.
thank you #Stephen Muecke and #Varun Vasishtha for pushing me there ;)
There must be a javascript error that is restricting jquery validation to work, try to debug using Firebug in Firefox
Exclude the last "test message":
#Html.ValidationMessageFor(model => model.Description)
See the documentation: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.validationextensions.validationmessagefor%28v=vs.118%29.aspx

Using Bootstrap dual listbox with ASP.NET MVC

I added the Bootstrap dual listbox plugin on my project and it's working fine, but how can I pass the contents of the selected listbox to my controller? It's already inside a form but if I try to get it through FormCollection it returns as null.
View:
<div class="form-group col-md-7" style="margin-left: -15px;">
<select style="display: none;" multiple="multiple" size="10" name="dualListbox" id="dualListbox" class="demo2">
#if (ViewData["Customers"] != null)
{
foreach (var item in ViewData["Customers"] as List<Testbox.Models.Customer>)
{
<option value="customer">#item.NAME #item.LName - #item.PHONE11</option>
}
}
</select>
</div>
Well you can do it as below:
I'll assume that your form id is demoform and below is how the post action method will look like:
[HttpPost]
public ActionResult GetForm()
{
string values = Request.Form["dualListbox"];
//Form[key] will be 'name' property of your select box
//You will get values as comma ',' separated values like option 1,
//option 2, option 4 etc., and I hope you know how you can get each
//options by splitting the comma separated values.
......
......
}
Here is an example to your question. Maybe this will help people in the future.
The trick is in the JS.
Let's say you want to use Bootstrap Dual Listbox in conjuction with ASP.NET MVC 4 and Kendo framework.
We will use the Razor syntax and C#.
First, we write in the view the placeholder for the code. We will be linking a kendo control and the Bootstrap Dual Listbox
<script>
var urlGetCascadeMultiSelectBrandTypeByBrand = "#(Url.Action("GetCascadeMultiSelectBrandTypeByBrand", "DropDownList"))";
</script>
<div class="col-md-12 col-sm-12 col-xs-12 padding-0 ">
<div class="col-md-6 col-sm-6 col-xs-12">
#Html.LabelFor(m => m.BrandId)<br />
#(Html.Kendo().DropDownListFor(m => m.BrandId)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeDdlBrandBySegment", "DropDownList")
.Data("filterSegments");
})
.ServerFiltering(true);
})
.DataTextField("BrandName")
.DataValueField("BrandId")
.Filter(FilterType.Contains)
.CascadeFrom("SegmentId")
.OptionLabel("Select brand")
.Events(evt => evt.Change("onBrandIdDdlChange"))
.HtmlAttributes(new { #style = "width: 100%;" }))
#Html.ValidationMessageFor(m => m.BrandId)
</div>
<div class="col-md-6 col-sm-6 col-xs-12">
</div>
</div>
<div class="clear height10"></div>
<div class="col-md-12 col-sm-12 col-xs-12 padding-0 ">
<div class="col-md-12 col-sm-12 col-xs-12">
#Html.LabelFor(m => m.BrandTypeIdList)<br />
#if (Model.IsEdit)
{
#Html.ListBoxFor(m => m.BrandTypeIdList, Html.GetBrandTypeByBrandIdSelectListItemsList(Model.BrandId))
}
else
{
#Html.ListBoxFor(m => m.BrandTypeIdList, new List<SelectListItem>())
}
#Html.ValidationMessageFor(m => m.BrandTypeIdList)
</div>
</div>
Then, we create the C# helper code to go with it.
public static IEnumerable<SelectListItem> GetBrandTypeByBrandIdSelectListItemsList(this HtmlHelper htmlHelper, int brandId)
{
using (var dbContext = new Entities())
{
return dbContext.BrandType.Where(x => x.Active == true && x.BrandId == brandId).Select(BrandTypeToDdlSelector).ToList();
}
}
public static Func<BrandType, SelectListItem> BrandTypeToDdlSelector
{
get
{
return (x => new SelectListItem()
{
Value = x.BrandTypeId.ToString(),
Text = x.Name
});
}
}
public JsonResult GetCascadeMultiSelectBrandTypeByBrand(int? brandId)
{
var brandTypesList = DbContext.BrandType.Where(p => p.Active == true);
if (brandId != null)
{
brandTypesList = brandTypesList.Where(p => p.BrandId == brandId);
}
return Json(brandTypesList.Select(x => new { BrandTypeId = x.BrandTypeId, BrandTypeName = x.Name }), JsonRequestBehavior.AllowGet);
}
Then we create the JS code to manipulate the HTML at runtime and bind the selected values to the MVC model.
var brandTypeIdDualListbox = new Object();
$(document).ready(function ()
{
//we create the dual list control
brandTypeIdDualListbox = $('select[name="BrandTypeIdList"]').bootstrapDualListbox({
nonSelectedListLabel: 'Non-selected',
selectedListLabel: 'Selected',
preserveSelectionOnMove: 'moved',
moveOnSelect: false,
});
//we setup the change event for the control
$('select[name="BrandTypeIdList').on('change', function (args)
{
//we traverse every option
$("#BrandTypeIdList option").each(function (index,element)
{
//we check if the element has the `data-sortindex` attribute
if (!!$(element).attr('data-sortindex'))
$(element).attr('selected', 'selected');
else
$(element).removeAttr('selected');
});
})
});
function filterBrands()
{
var brandId = $("#BrandId").val();
if (brandId == "")
brandId = "-1";
return {
BrandId: brandId
};
}
function populateBrandTypeIdDualListbox()
{
$.getJSON(urlGetCascadeMultiSelectBrandTypeByBrand, filterBrands(), function (data)
{
var items;
$.each(data, function (i, item)
{
brandTypeIdDualListbox.append("<option value=" + item.BrandTypeId/*Value*/ + ">" + item.BrandTypeName/*Key or Text*/ + "</option>");
});
brandTypeIdDualListbox.trigger('bootstrapDualListbox.refresh', true); // we refresh the control
});
}
function onBrandIdDdlChange(evt)
{
var brandIdDropDownList = $("#BrandId").data("kendoDropDownList");
$('#BrandTypeIdList').empty();
brandTypeIdDualListbox.trigger('bootstrapDualListbox.refresh', true);
if ($("#BrandId").val() == "" || $("#BrandId").val() == "-1")
{
//if no value is selected we disable the control
$(".bootstrap-duallistbox-container").find("*").prop("disabled", true);
}
else
{
populateBrandTypeIdDualListbox();
$(".bootstrap-duallistbox-container").find("*").prop("disabled", false); // we enable the control
}
}

Resources