I need to add switch control to my web application.
I'm trying to use Kendo Switch control.
I want to bind my switch to a model property.
I do that with a following way:
<div class="form-group">
#Html.Label("Guest Mode:")
<label class="checkbox-inline">
#Html.CheckBoxFor(m => m.SomeProperty, new {#id = "switch"})
</label>
</div>
<script>
var switchInstance = $("#switch").kendoMobileSwitch();
</script>
I tried many ways but can not render so simply control properly (see my screenshot).
Also I tried to use only razor syntax but it rendered only a checkbox.
What is my problem and how to fix it?
Thanks for advance!
I've done it like that. The goal is to switch on/off 'disabled' attribute for some text fields. In my case this way works just fine. I hope it's useful.
In the label tag 'for' is the binding with model property method. Checkbox is bound with the model by Html helper.
<div class="custom-control custom-switch">
#Html.CheckBoxFor(m => m.Enabled, new { #class = "custom-control-input" })
<label class="custom-control-label" for="Enabled">Disable</label>
</div>
and next is jQuery script:
#section Scripts {
<script type="text/javascript">
$(document).ready(DOM_Load);
function DOM_Load(e) {
$('[data-toggle="popover"]').popover({
container: "body"
});
$("div.custom-switch").children("input").on("change", EnabledToggle_Change);
}
function EnabledToggle_Change(e) {
var inputs = $("div.container-fluid").find("input[type!='checkbox']");
var textareas = $("div.container-fluid").find("textarea");
var switchLabel = $("div.custom-switch").children(".custom-control-label");
switchLabel.text(switchLabel.text() == 'Disable' ? 'Enable' : 'Disable');
inputs.prop('disabled', (i, v) => !v);
textareas.prop('disabled', (i, v) => !v);
}
</script>
}
Related
I am using MVC and in View i want to bind a textbox to google API to get auto complete address, How to do this in MVC??
Note: I dont want to display google maps. just textbox show suggestions .. I Did something like this
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAacPaT9YiOu-8leoacd1RDbRfx7an1u74&libraries=places&callback=initMap"
async defer></script>
<script>
google.maps.event.addDomListener(AddNewJob, 'load', function () {
var options = {
types: ['(cities)'],
componentRestrictions: { country: "in" }
};
});
autocomplete = new google.maps.places.Autocomplete(document.getElementById('FromAddress'));
autocomplete.addListener();
</script>
}
And in textBox
<div class="form-group">
#Html.LabelFor(model => model.FromAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="text" id="FromAddress" />
#Html.ValidationMessageFor(model => model.FromAddress, "", new { #class = "text-danger" })
</div>
</div>
var input = document.getElementById('your input tag id');
var autocomplete = new google.maps.places.Autocomplete(input);
Use javascript to do it. Follow api documentation
Check it out on jsfiddle
To do this, you'll need a Maps API Key which you can obtain here : https://developers.google.com/maps/documentation/embed/get-api-key.
Replace YOUR_API_KEY in the scripts url with the api key you obtain from the link above.
Change the id to match the id of the input element you want to attach this to. In the example below, the input element's id is "FromAddress".
And you might want to change options or remove it entirely depending on your needs as the current setting limits the auto-completion to cities in India.
#section Scripts {
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async="" defer=""></script>
<script>
function initMap() {
google.maps.event.addDomListener(window, 'load', function () {
var options = {
types: ['(cities)'],
componentRestrictions: { country: "in" }
};
var input = document.getElementById('FromAddress');
var places = new google.maps.places.Autocomplete(input, options);
});
}
</script>
}
I have a MVC form which is more complex than all of my others, utilising three models.
Company -> Base_IP -> RequestedIP which goes ViewModel -> Partial1 -> Partial2
I am using BeginCollectionItem for this has each model has a property list of the the model down from it. IE - Company has a property called baseIps, the BaseIp class has a property called requestedIps, it is requestedIps that is coming back null, the count is there on page render, but is not on submit.
When submitting to the database in the post Create(), I get nulls on the 'requestedIps' property, why is this?
I've added the offending controller and partial code samples below, not the entire thing as it's massive/redundant - any questions, please let me know.
Controller - [HttpGet]Create()
public ActionResult Create()
{
var cmp = new Company
{
contacts = new List<Contact>
{
new Contact { email = "", name = "", telephone = "" }
}, pa_ipv4s = new List<Pa_Ipv4>
{
new Pa_Ipv4
{
ipType = "Pa_IPv4", registedAddress = false, existingNotes = "", numberOfAddresses = 0, returnedAddressSpace = false, additionalInformation = "",
requestedIps = new List<IpAllocation>
{
new IpAllocation { allocationType = "Requested", cidr = "", mask = "", subnet = "" }
}
}
}
};
return View(cmp);
}
Controller - [HttpPost]Create()
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Company cmp) // does not contain properties assigned/added to in view render
{
if (ModelState.IsValid)
{
db.companys.Add(cmp);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(cmp);
}
Create View
#model Company
#using (Html.BeginForm())
{
<div id="editorRowsAsn">
#foreach (var ip in Model.pa_ipv4s)
{
#Html.Partial("Pa_IPv4View", ip)
}
</div>
<br />
<div data-role="main" class="ui-content">
<div data-role="controlgroup" data-type="horizontal">
<input type="submit" class="ui-btn" value="Create" />
</div>
</div>
}
Pa_Ipv4 View
#model Pa_Ipv4
#using (Html.BeginCollectionItem("pa_ipv4s"))
{
#Html.AntiForgeryToken()
<div id="editorRowsRIpM">
#foreach (var item in Model.requestedIps)
{
#Html.Partial("RequestedIpView", item)
}
</div>
#Html.ActionLink("Add", "RequestedManager", null, new { id = "addItemRIpM", #class = "button" }
}
RequestedIpView
#model IpAllocation
<div class="editorRow">
#using (Html.BeginCollectionItem("requestedIps"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.subnet, new { #class = "checkFiller" })
</span>
</div>
<div class="ui-block-b">
<span>
#Html.TextBoxFor(m => m.cidr, new { #class = "checkFiller" })
</span>
</div>
<div class="ui-block-c">
<span>
#Html.TextBoxFor(m => m.mask, new { #class = "checkFiller" })
<span class="dltBtn">
<img src="~/Images/DeleteRed.png" style="width: 15px; height: 15px;" />
</span>
</span>
</div>
</div>
}
</div>
You first (outer) partial will be generating correct name attributes that relate to your model (your code does not show any controls in the Pa_Ipv4.cshtml view but I assume you do have some), for example
<input name="pa_ipv4s[xxx-xxx].someProperty ...>
however the inner partial will not because #using (Html.BeginCollectionItem("requestedIps")) will generate
<input name="requestedIps[xxx-xxx].subnet ...>
<input name="requestedIps[xxx-xxx].cidr ...>
where they should be
<input name="pa_ipv4s[xxx-xxx].requestedIps[yyy-yyy].subnet ...>
<input name="pa_ipv4s[xxx-xxx].requestedIps[yyy-yyy].cidr ...>
Normally you can pass the prefix to the partial using additional view data (refer this answer for an example), but unfortunately, you do not have access to the Guid generated by the BeginCollectionItem helper so its not possible to correctly prefix the name attribute.
The articles here and here discuss creating your own helper for handling nested collections.
Other options include using nested for loops and including hidden inputs for the collection indexer which will allow you to delete items from the collection and still be able to bind to your model when you submit the form.
for (int i = 0; i < Model.pa_ipv4s.Count; i++)
{
for(int j = 0; j < Model.pa_ipv4s[i].requestedIps.Count; j++)
{
var name = String.Format("pa_ipv4s[{0}].requestedIps.Index", i);
#Html.TextBoxFor(m => m.pa_ipv4s[i].requestedIps[j].subnet)
#Html.TextBoxFor(m => m.pa_ipv4s[i].requestedIps[j].cidr)
...
<input type="hidden" name="#name" value="#j" />
}
}
However if you also need to dynamically add new items you would need to use javascript to generate the html (refer examples here and here)
If you look at your final markup you will probably have inputs with names like
input name="subnet"
input name="cidr"
input name="mask"
This is how the form collection will appear when the form gets posted. Unfortunately this will not bind to your Company model.
Your fields will need to look like this instead
input name="Company.pa_ipv4s[0].subnet"
input name="Company.pa_ipv4s[0].cidr"
input name="Company.pa_ipv4s[0].mask"
input name="Company.pa_ipv4s[1].subnet"
input name="Company.pa_ipv4s[1].cidr"
input name="Company.pa_ipv4s[1].mask"
There are multiple ways to "fix" this, and each has its own caveats.
One approach is to setup "Editor" views (typically in ~/Views/Shared/EditorTemplates/ClassName.cshtml), and then use #Html.EditorFor(x => x.SomeEnumerable). This will not work well in a scenario in which you need to be able to delete arbitrary items from the middle of a collection; although you can still handle those cases by means of an extra property like ItemIsDeleted that you set (e.g. via javascript).
Setting up a complete example here would be lengthy, but you can also reference this tutorial: http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/
As a start, you would create a simple template like
~/Views/Share/EditorTemplates/Contact.cshtml:
#model yournamespace.Contact
<div>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name)
#Html.ValidationMessageFor(c => c.Name)
</div>
<div>
#Html.LabelFor(c => c.Email)
#Html.TextBoxFor(c => c.Email)
#Html.ValidationMessageFor(c => c.Email)
</div>
... other simple non-enumerable properties of `Contact` ...
#Html.EditorFor(c => c.pa_ipv4s) #* uses ~/Views/Shared/EditorTemplates/pa_ipv4s.cshtml *#
In your view to edit/create a Company, you would invoke this as
#Html.EditorFor(company => company.Contacts)
(Just like the EditorTemplate for Company invokes the EditorFor pa_ipv4s.)
When you use EditorFor in this way, MVC will handle the indexing automatically for you. (How you handle adding a new contact/IPv4/etc. here is a little more advanced, but this should get you started.)
MVCContrib also has some helper methods you can use for this, but it's not particularly simple from what I recall, and may tie you down to a particular MVC version.
All,
I need to add validation rules to dynamic form input text elements added by the user.
I am accomplishing this by cloning a chunk of HTML, providing unique ids and adding to the DOM
I researched the syntax for this, which I believe is correct yet I am getting the following JS error when I try to access the .rules method:
TypeError: $(...).rules is not a function
Caused by this:
$("input[type=text].validateRequired").each(function () {
$(this).rules("add", { required: true, messages: { required: "Data is missing" }
});
});
When I examine $(this) in FireBug, I do not see a .rules method yet it exists in the validation scripts and all of the documentation shows that the method should be available globally. Not sure how to get it in scope.
Here are the code pieces in the View related to this problem:
JS Includes
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
JS Method that creates the dynamic form elements
<script type="text/javascript">
$(document).ready(function() {
var uniqueId = 1;
var ctr = 1;
$(function() {
$('.js-add-cosponsor-hyperlink').click(function() {
var copy = $("#cosponsorsTemplate").clone(true).appendTo("#addCosponsorSection").hide().fadeIn('slow');
var cosponsorDivId = 'cosponsors_' + uniqueId;
var copyText = copy.html();
copyText = copyText.replace(/Guitar1/g, 'Guitar' + ctr);
copyText = copyText.replace('Guitar_1', 'Guitar_' + ctr);
copy.html(copyText);
$('#cosponsorsTemplate').attr('id', cosponsorDivId);
var deleteLink = copy.find("a.icon.delete");
deleteLink.on('click', function() {
copy.fadeOut(300, function() { $(this).remove(); }); //fade out the removal
});
$.validator.unobtrusive.parse(form);
$("input[type=text].validateRequired").each(function () {
var t = $(this);
$(this).rules("add", { required: true, messages: { required: "Data is missing" } });
});
uniqueId++;
ctr++;
});
});
});
</script>
*The Form*
#using (Html.BeginForm())
{
[...]
<!-- Template used to do the Clone: These need dynamic validation -->
<div style="display:none">
<div id="cosponsorsTemplate">
<div class="formColumn1"><label>Guitar</label></div>
<div class="formColumn2">#Html.TextBoxFor(model => model.Guitar1.Make, new { Placeholder = "Make", Class = "validateRequired" })
<div class="messageBottom">
#Html.ValidationMessageFor(model => model.Guitar1.Make)
</div>
</div>
<div class="formColumn3">#Html.TextBoxFor(model => model.Guitar1.Model, new { Placeholder = "Model" , Class = "validateRequired"})
<div class="messageBottom">
#Html.ValidationMessageFor(model => model.Guitar1.Model)
</div>
</div>
<div class="formColumn4">#Html.TextBoxFor(model => model.Guitar1.ProductionYear, new { Placeholder = "Production Year", Class = "validateRequired" })
<div class="messageBottom">
#Html.ValidationMessageFor(model => model.Guitar1.ProductionYear)
</div><a class="icon delete">Delete</a>
</div>
</div>
</div>
<!-- End Add Co-Sponsor Row Template -->
}
You are cloning a chunk of HTML so every time you do a clone you need to parse the whole form
by using $.validator.unobtrusive.parse
I have this script, what it intends to do is: in a view with a list of contacts, each one with a edit link whenever you click on one of these links it displays an edit form in a partial view (there's only one div in the parent view for holding it) just below the clicked contact, for that it does a get ajax call to the server and gets the information for that contact. After submitting, via ajax as well, it refreshes the list.
Everything seems to work fine, but if I edit a contact, after the list being refreshed I try to open again the form on the same contact and the information is the same as it was before being edited. Although debugging I see the list for the server is correct (and so is the display in the list, it's only wrong in the form)
Thing is that in chrome developer tool I can see the form with some "default values" set to the previous stuff. I didn't know about them till now and I don't know how to get rid of them, because to my understanding I'm making a get call to the server, anyway I have tried this
document.getElementById("editForm").reset();
with no luck.
Thanks
The script
(function ($) {
var editContainer = $(document.getElementById('editContainer'));
$('#editContainer').on('submit', '#editForm', ajaxEditCall);
$('a.edit').on("click", displayEditForm);
function displayEditForm(e) {
var clickedElement = $(this).parent(),
url = editContainer.data('amp-edit-url');
$.get(url, {
id: parseInt(this.id, 10)
}, function (result) {
editContainer.html(result);
$.validator.unobtrusive.parse(editContainer);
// Display edit form just below the "item" clicked
if (editContainer.is(":visible")) {
editContainer.slideToggle(300, function () {
editContainer.appendTo(clickedElement);
editContainer.slideToggle(300);
});
} else {
editContainer.appendTo(clickedElement);
editContainer.slideToggle(300);
}
}, "html");
e.preventDefault();
}
function ajaxEditCall(e) {
e.preventDefault();
//if ($('#editForm').valid()) {
var list = $(document.getElementById('list'));
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.passedValidation == true) {
$.get(result.action, function (partial) {
document.getElementById("editForm").reset();
list.html(partial);
$('a.edit').on("click", displayEditForm);
$('#editForm').slideUp(300);
setTimeout(function () {
list.effect("highlight", {}, 3000);
}, 1000);
});
} else {
$(document).scrollTop(0);
editContainer.html(result);
$.validator.unobtrusive.parse('#editForm');
}
}
});
//} return false;
}
}(jQuery));
And the view in case is relevant
#model ContactListViewModel
#{
ViewBag.Title = " My Contacts";
}
<div id="myContacts">
<h2>My Contacts</h2>
<div id="editContainer" data-amp-edit-url="#Url.Action("Edit", "Contacts")" class="initiallyHidden"></div>
<div id="list">
#{ Html.RenderPartial("_ContactList", Model); }
</div>
<div id="dialog" data-amp-del-url="#Url.Action("Delete", "Contacts")" title="Confirmation Required">
<p>Are you sure you want to delete this Contact?</p>
</div>
</div>
#section Foot
{
<script src="~/Scripts/AMPContacts.js"></script>
<script src="~/Scripts/conditional-validation.js"></script>
<script src="~/Scripts/Placeholders.min.js"></script>
}
Well that's obviously the parent view, the partial one is just a bunch of fields, I remove most of them to avoid increase the already long post
#model AddContactViewModel
#using (Html.BeginForm("Edit", "Contacts", FormMethod.Post, new { #id = "editForm", #class = "addTab" }))
{
#Html.ValidationSummary(true, "Please correct the errors and try again.")
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.OwnedItemId)
#Html.HiddenFor(m => m.AddressId)
<div id="editContactDetails">
<div>
#Html.DisplayFor(m => m.PlanName)
</div>
<div>
#Html.DropDownListFor(m => m.Title, Model.TitleList, "Title")
</div>
<div>
#Html.EditorFor(m => m.FirstName, new { #id="editFirstName", data_placeholders_focus = "false", placeholder = ViewData.ModelMetadata.Watermark })
#Html.ValidationMessageFor(m => m.FirstName)
</div>
// And so on....
<div class="addDEC">
<input class="addDECButton" type="submit" value="Save" />
</div>
}
I ran into this problem with a site I was working on. You'll need to disable your ajax caching:
//Disbable cache for all jQuery AJAX requests
$.ajaxSetup({ cache: false });
That will do it for all ajax calls, so you may only want to do that on certain pages, depending on your usage.
So I use a list of string to fill a DropDownList it work fine but for the edit part when the user goes to the edit view I need that Relacion have the value is have been saved on the db, selected in the DropDownList. how can dothat?
List<string> x = new List<string> { "string1", "string2", "string3", " string4" };
ViewBag.Relacion = new SelectList(x);
<div class="editor-label">
#Html.LabelFor(model => model.Relacion)
</div>
<div class="editor-field">
#Html.DropDownList("Relacion")
#Html.ValidationMessageFor(model => model.Relacion)
</div>
you need to provide values to your dropdown list not only text strings
if your model does not know about relaction selected value you may use javascrip and do something like this
<script type="text/javascript">
$(document).ready(function () {
$('select[name=Relacion]').val($('#Relaciontext').val());
}
</script>
<div class="editor-field" style="display:none" >
#Html.TextBox("Relaciontext", ViewData["statecode"])
</div>
#Html.DropDownList("Relacion")
ViewData["statecode"]="string1";
but Ideally you need to use the selected list to populate your dropdown list and then model
by creating select list
#Html.DropDownListFor(model => model.Relacion, (IEnumerable<SelectListItem>)ViewData["Relacion"])
I would suggest you to use Telerik controls. They have DropDownList, Combobox, Grid and many more. It's an open source project with many many users.
See this DEMO