The appended items work perfectly when not including the 2nd Script(which is what gives the listbox a sleek looking listbox with checkboxes in it) - but when I do include it, then it doesnt append the items.
Is there any reason why ?
JQuery:
$("#ddlistcategory").change(function () {
var catItem = $("#ddlistcategory").val();
$("#ddlistaccountitems").empty();
$.ajax({
url: '#Url.Action("GetCategories", "Account")',
dataType: "json",
type: "Post",
data: { "i": catItem },
success: function (data) {
$.each(data, function (key, val) {
//alert(key + " " + val);
$("#ddlistaccountitems").append('<option id="' + key + '">' + val + '</option>');
})
}
});
});
$('#ddlistaccountitems').multiselect({
includeSelectAllOption: false,
allSelectedText: 'No option left ...',
enableFiltering: true,
filterPlaceholder: 'Search for something...'
});
View:
<div class="form-group form-group-sm">
#Html.Label("Items", new { #class = "control-label" })
#Html.ListBoxFor(x => x.SelectedAccountItems, Model.UserItems, new { #class = "form-control", #id = "ddlistaccountitems", #multiple = "multiple" })
</div>
You are calling multiselect outside of your ajax method which is populating the element with the options. As a result you will be initializing it before the ajax has finished, so the issue is most likely that the initialization does not yet have the options to build from.
To fix this, move the initialization into the success method so it will execute after the ajax has finished and all the data that it needs has been created.
Your Ajax call will work asynchronously. That is, the .multiselect will execute before the options appended. .multiselect will hide your actual select and replace it with custom html. So you have to fill it before .multiselect execution. add
async: false
in Ajax call or call
$('#ddlistaccountitems').multiselect()
inside that success function.
Related
I am new and struggling to find a way to create a searchable dropdownlist (MVC5/C#). I have tried Select2, and could not get it working. I am desperate and out of time.
Looking at a few tutorials on Jquery Autocomplete, it seems pretty straight and forward. My problem is that all of the examples on line seems to use static data. My dropdownlist is populated from my Controller using a List of pre-filtered results.
This is how I populate my doprdownlist
List<SelectListItem> autocomplete = db.ICS_Supplies.Where(s => s.InvType == "F").Select(x => new SelectListItem { Value = x.Supplies_ID.ToString(), Text = x.Old_ItemID + " " + " | " + " " + " Description: " + x.ItemDescription, Selected = false }).DistinctBy(p => p.Text).OrderBy(p => p.Text).ToList();
ViewBag.FormsList = new SelectList(autocomplete, "Value", "Text");
As is, the dropdown populates - but it has a lot of records and is VERY slow.
From most of the examples I have seen online, the searchable items are something like:
var options = [
{ value: 'Adam', data: 'AD' },
// ...
{ value: 'Tim', data: 'TM' }
];
That's great, if I want to type out a thousand possible items - but I need to populate my DropDownList options from a table. .. and I am lost.
I am very new to Jquery and any direction is greatly appreciated.
EDIT1*
I am adding the View Code (from the online Example) for more clarification
<div class="form-group col-sm-5">
<label for="files">Select Supply:</label>
<input type="text" name="supplies" id="autocomplete" />
</div>
<div>
Selected Option : <span class="label label-default" id="selected_option"></span>
</div>
I suggest you need ajax to get a dynamic autocomplete list. Here's some sample code - it's the definition of a basic jQuery implementation that uses ajax.
function close_autocomplete($elemid) {
jQuery($elemid).autocomplete("destroy" );
}
function attach_autocomplete($elemid) {
jQuery($elemid)
.autocomplete({
delay : 250,
minLength : 3,
source : function( request, response ) {
var $thedata = request.term;
jQuery.ajax({
url : myajaxresponder.php,
type : "GET",
data : {
action_id : "autocomplete",
thedata : $thedata
},
error : function (jqXHR, textStatus, errorThrown){
console.log(textStatus + " " + errorThrown);
response("");
},
success : function (result) {
var resultarray = JSON.parse(result);
response(resultarray);
}
});
},
select : function ( event, ui ) {
jQuery($elemid).val(ui.item.value);
return false;
},
})
}
// attach the handlers
jQuery("#myid").focus(function ()
{attach_autocomplete(jQuery(this).prop("id"))});
jQuery("#myid").blur(function ()
{close_autocomplete(jQuery(this).prop("id"))});
I'm trying to implement the CKEditor for a blog. I've got the Create Blog working fine, but for some reason the Edit Blog page does not display content which already exists.
If I remove the CKEditor.replace script, then the normal EditorFor displays fine. See images below.
I've read lots of posts, as well as the CKEditor documentation, and what I'm doing is supposedly correct.
Is there a trick to get the pre-existing data to show in the CKEDITOR content area?
Here's the JS to add the CKEDITOR
<script>CKEDITOR.replace("MainContent")</script>
Here's the HTML.
<div class="col-md-10">
#Html.EditorFor(model => model.Content,
new { htmlAttributes =
new { #id = "MainContent", #class = "form-control" } })
</div>
When the CKEDITOR.replace is used, it looks like this... no data shows in the Content area.
When the CKEDITOR.replace is removed, it looks like this, the content displays correctly
ok, I'm not sure why it does not work out of the box the way it is described, but I added a bit of JavaScript and now it's working. I'd still love input on why it does not work as described.
$.ajax({
url: 'Blog/Edit',
type: 'POST',
data: JSON.stringify(Blog),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.success == true) {
window.location.href = "../Blog";
}
else if (data.success == false) {
alert("Error occured..!!")
}
},
error: function () {
alert("Error occured..!!");
},
});
Basically I am assigning roles to the users. I want to automatically show the pre-asssigned roles. I am able to render that on the first time, but the checkboxes remains same when value is changed in dropdown:
type: "POST",
dataType: "json",
url: "/UserRoles/myaction",
data: { "userid": DropDownSelectedVal },
success: function (data) {
$.each(data, function (i, val) {
var a = (data[i]);
$("#" + a).attr('checked', true);
});
},
error: function (error) {
alert('error; ' + eval(error));
}
})
First try to clear all check boxes using the below code on selection change event of dropdown.
$('input:checkbox').removeAttr('checked');
Then run your ajax code for selecting new user roles.
type: "POST",
dataType: "json",
url: "/UserRoles/myaction",
data: { "userid": DropDownSelectedVal },
success: function (data) {
$.each(data, function (i, val) {
$("#" + val).prop('checked', true);
});
},
error: function (error) {
alert('error; ' + eval(error));
}
})
You should control all checkbox. You can try this.
url: "/UserRoles/myaction",
data: { "userid": DropDownSelectedVal },
success: function (data) {
$.each(data, function (i, val) {
var a = (data[i]);
if(!$("#" + a).is(":checked")) {
$("#" + a).attr("checked", true);
}else{
$("#" + a).attr("checked", false);
}
});
},
The elegant solution that I can suggest is to maintain a hidden input to store all your permission that is selected.
Your HTML
<input type="hidden" id="_hiddenSelectedPermissions" value="2, 1" />
<input class="permissions" type="checkbox" value="1">Default Permission 1
<input class="permissions" type="checkbox" value="2">Default Permission 2
<input class="permissions" type="checkbox" value="3">Permission 3
<input class="permissions" type="checkbox" value="4">Permission 4
<input class="permissions" type="checkbox" value="5">Permission 5
Set the hidden control value after ajax results and call below function to reassign all the checked check boxes
function refreshSelectedPermissions() {
$('input:checkbox.permissions').prop('checked', false);
var selected = $('#_hiddenSelectedPermissions').val().split(",") || [];
$('input:checkbox.permissions').each(function() {
var value = $(this).val();
if($.inArray(value, selected) === -1){
$(this).prop('checked', false);
}
else{
$(this).prop('checked', true);
}
});
}
I have the following code:
#Ajax.ActionLink("Settings", "SettingsPopup", "Settings",
new { area = "Customer" },
new AjaxOptions()
{
HttpMethod = "Get",
UpdateTargetId = "settings-content",
InsertionMode = InsertionMode.Replace,
OnSuccess = "settingsPopupLoaded",
AllowCache = true
},
new { #class = "profile-right__a icon-help" })
I need to add <i class="sub"></i> element inside this liks as:
<i class="sub"></i>
How to do this?
When you want to have customized markup but still want the ajaxy behavior. You can simply use jQuery to wire up that (That is what the ajax helpers also does)
<a class="ajaxy" targetid="settings-content"
href="#Url.Action("settingsPopup","Settings",new { area="Customer"})">
<span class="glyphicon glyphicon-user text-#userLevel"></span>
</a>
The javascript will be quite simply, simply look for the elements with the css class "ajaxy", make an ajax call using jQuery $.get method and update the DOM element with the result coming back.
function settingsPopupLoaded(e) {
console.log('settingsPopupLoaded', e);
}
$(function () {
$(".ajaxy").click(function (e) {
e.preventDefault();
var _this = $(this);
$.get(_this.attr("href"), function (res) {
var tId = _this.attr("targetid");
$("#" + tId).html(res);
settingsPopupLoaded(res);
});
});
});
You can also use $.load method if it is simply updating the DOM element with the response from the ajax call.
I have the below form
<form class="regForm" id="frmRegistration" method="post">
<h3>Register Customer Patient</h3>
#Html.ValidationSummary(true)
#Html.LabelFor(m => m.LastName)
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control cfield", required = "required", autofocus = "autofocus" })
#Html.LabelFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control cfield", required = "required" })
#Html.LabelFor(m => m.MiddleName)
#Html.TextBoxFor(m => m.MiddleName, new { #class = "form-control cfield", required = "required" })
#Html.LabelFor(m => m.BirthDate)
#Html.TextBoxFor(m => m.BirthDate, new { #class = "form-control cfield", required = "required" })
#Html.LabelFor(m => m.Address)
#Html.TextBoxFor(m => m.Address, new { #class = "form-control cfield", required = "required" })
<button type="submit" id="btnSave" class="btnreg btn btn-primary form-control">REGISTER</button>
<button type="button" onclick="clearTexts();" class="btnClear btn btn-danger form-control">CLEAR</button>
Below is the controller action method which I want to trigger/call
[HttpPost]
public ActionResult AddCustomerPatient(Customer _Customer)
{
using (var db = new DCDBEntities())
{
db.Customers.Add(_Customer);
db.SaveChanges();
}
return Json(new {registeredCustomer="ok"});
}
Below is my jquery ajax which doesn't work
$("#btnSave").click(function () {
e.preventDefault();
var PotentialCustomer = {
"LastName": 'A',
"FirstName": 'A',
"MiddleName": 'A',
"BirthDate": 'A',
"Address": 'A'
};
$.ajax({
type: 'POST',
url: '/Registration/AddCustomerPatient',
data: 'JSON.stringify(PotentialCustomer),',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
});
Problem 1.) The controller action method is not getting hit ( I placed a breakpoint)
Problem 2.) How can I pass the Model to the controller action method and save it via linq to entities.
I've been searching and tried a lot but still not able to get it done.
Below is the routconfig
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I tried to put a breakpoint in the GET or first method of my controller , whenever I click the "REGISTER" button it gets hit and not the [HttpPost] , why is that?
public ActionResult RegisterCustomerPatient()
{
return View();
}
[HttpPost]
public ActionResult AddCustomerPatient(Customer _Customer)
{
using (var db = new DCDBEntities())
{
db.Customers.Add(_Customer);
db.SaveChanges();
}
return Json(new {registeredCustomer="ok"});
}
do i need to create a view for HTTPPOST action method?
var formData = $('#frmRegistration').serialize();
$.ajax({
type: 'POST',
url: '#Url.Action("AddCustomerPatient", "Registration")',
data: formData,
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
better to serialize the form data and send it to controller action method
data: 'JSON.stringify(PotentialCustomer),'
Please remove single quotes .
It will be fine
data: JSON.stringify(PotentialCustomer),
Problem is line
data: 'JSON.stringify(PotentialCustomer),',
and
click(function () {
// e is undefined here. Add e as parameter in function.
e.preventDefault();
JSON.stringify should be used as funtion not string. In above it is used as string. Change it to following (assuming all fields are string in model)
$("#btnSave").click(function (e) {
e.preventDefault();
var PotentialCustomer = {
"LastName": 'A',
"FirstName": 'A',
"MiddleName": 'A',
"BirthDate": 'A',
"Address": 'A'
};
$.ajax({
type: 'POST',
url: '/Registration/AddCustomerPatient',
data: JSON.stringify(PotentialCustomer),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
there is a , inside data
data: 'JSON.stringify(PotentialCustomer),',
next am not sure but try
data:{'_customer':'PotentialCustomer'};
instead of data.strinify
Problem 1.) The controller action method is not getting hit
I think it is caused by wrong URL of ajax post. You could try to open Network tab of Developer Tool on Browser to confirm that. It you ajax post return HTTP status 404, you should update the URL of your ajax post.
One way to get correct URL is using the #Url.Action to add URL attribute of your submit button.
<button type='button' id='btnSave' data-url='#Url.Action("AddCustomerPatient", "Registration")' class='btnreg btn btn-primary form-control'>REGISTER</button>
Then you could get this value inside click function like this
$("#btnSave").data('url')
Problem 2.) How can I pass the Model to the controller action method and save it via linq to entities.
After getting correct URL, you should update your click function
$("#btnSave").click(function () {
var formData = $('#frmRegistration').serialize();
$.ajax({
type: 'POST',
url: $("#btnSave").data('url'),
data: formData,
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
});
Alternative method
I guess you want to make an ajax post instead of submit form, so you could try another simple method as below.
The razor code
#using (Html.BeginForm("AddCustomerPatient", "Registration", FormMethod.Post, new { id = "frmRegistration"))
{
...
<button type="submit" id="btnSave" class="btnreg btn btn-primary form-control">REGISTER</button>
<button type="button" onclick="clearTexts();" class="btnClear btn btn-danger form-control">CLEAR</button>
}
The script
$(function () {
$("#frmRegistration").on('submit', function (e) {
e.preventDefault(); // prevent the form's normal submission
var $form = $(this);
var dataToPost = $form.serialize();
$.post($form.attr('action'), dataToPost)
.done(function(response, status, jqxhr){
// this is the "success" callback
})
.fail(function(jqxhr, status, error){
// this is the ""error"" callback
});
})
})
your ajax request should be like this
$("#btnSave").click(function (e) { //added e
e.preventDefault();
var _Customer= { //changed the name to name of parameter of action
"LastName": $("#LastName").val(),
"FirstName": $("#FirstName").val(),
"MiddleName": $("#MiddleName").val(),
"BirthDate": $("#BirthDate").val(),
"Address": $("#Address").val()
};
$.ajax({
type: 'POST',
url: '/Registration/AddCustomerPatient',
data: JSON.stringify(_Customer), //removed '' and corrected the format
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
});
JSON.stringify is a function so it should not be placed inside '' and JSON.stringify(_Customer) object name should match the name of parameter of Action which is Customer _Customer and also you used e.preventDefault(); without adding e in parameter