Passing DOM element to controller when using jquery autocomplete - asp.net-mvc

I am using ASP.Net MVC and JQuery UI autocomplete.
I have a number of input-boxes set up in a table and I have this JavaScript code.
$('.searchfield').autocomplete({
source: '#Url.Action("AutoCompleteFunction")'
});
Which works perfectly. The controller reads from a database and returns a list of matches.
Now I have another column of fields that also need autocomplete. However, these autocomplete lists have to be dependent on what is already in the table.
How can I pass DOM elements to the autocomplete controller?
I have tried something like this. As long as I only pass a string it will work, but not when I try to pass it a DOM element.
$('.newsearch').autocomplete({
source: '#Url.Action("NewAutoCompleteFunction", new { firstParameter = "testing"})'.replace("testing", "'$document.activeElement.value'")
});

Related

Saving Cascading drop downs in MVC

I have cascading dropdowns in my MVC partial view. DD1 drives the values in DD2. When I select DD1 I want DD2 to be populated with, based on a DB table, the correct values based on DD1's value.
My thought was to make DD2 a partial view and nest in my form. Then, with ajax, I can tell the partial view to refresh and pass it the value of DD1.
The problem is, when I submit the whole view (with both DD1 and DD2 and a bucnh of other stuff, how do I get the value that is in DD2?
I'm trying to solve this problem using MVC, rather than triggering a javascript function on change of DD1 to make a JSON call to get the options and then using javascript to modify DD2 to the correct values.
How should I do this?
How big are your value sets for each drop down?
I was attempting to do this same thing a few years ago. DD1 was United States and Canada, and DD2 was the associated States and Provinces. If your data set is relatively small, you're better off just putting all the select list markup for both cases in the page, and then swapping it out with javascript (jQuery). You'll be saving yourself the request round trip, regardless of whether you go ajax or a full page refresh.
If the data set is large and it doesn't make sense to put all values in the markup, and you want to use MVC views instead of modifying the DOM with an ajax call, then just refresh the entire page. If you want to go ajax, then just modify the DOM with jQuery; you don't need a partial view to accomplish this.
You are going to have to use javascript unless you want to do an entire page postback. For this type of thing, javascript/ajax is the way to go. I personally had a hard time when I switched to MVC having to accept that all this business logic was happening outside of the MVC model. But in the end, it's whatever makes the website work best (user doesn't see your code and know how pretty it is).
Anyway, partials won't work either unless you post the whole page since without using javascript, the partial is rendered as part of that page/form.
I would just add a onchange event to the first dropdown that triggers a json call to a method in the same controller...something like
...jquery...
$("#mydropdown").change(function() {
$.post("/Controller/DropdownChangedJSON", { firstdropdownvalue: $("#mydropdown").val() }, function(data) {
$("#seconddropdown").empty();
// loop through "data" to populate dropdown
}); //post
}); //mydropdown_change()
and in your controller:
public JsonResult DropdownChangedJSON(string firstdropdownvalue) {
//get results
List<datamodel> myarray = //something
return new JsonResult { Data = new { success = true, rows = myarray } };
}
hope this helps

Pass multiple html parameter with BeginForm

I need to send parameters with values ​​in a BeginForm html.
Example:
# using (Html.BeginForm ("Create", "IncomeDeclaration", new {declarationAmount = document.getElementById ("element"). value}))
This value I can not get from the Model, as it is not found in the model.
I've tried several ways and nothing worked. If you could change the content of a ViewBag that'd be great.
I appreciate your support.
You can't mix and match Javascript (document.getElementById ("element")) with the C# form declaration. If you want a value submitted with the form, you should add a relevant form element inside the form declaration. If you don't want a regular form element (eg. a textbox), you can use a "hidden" input field. If you want, you can dynamically populate the hidden field using javascript.

Passing edited value contenteditable field from view to controller in Rails

I am using Rails 3.1 to build a web form which, among other fields, contains a table whose cells can be edited. I require to save the text of edited cell in a database.
I am thinking of using HTML5 attribute 'contenteditable'. I can use the value of innerHTML of the cell . How can I pass this value to Rails controller (from the view)? Is it possible to use params to pass the data? Any suggestions?
HTML containers marked as contenteditable won't automatically be passed along to the server with a form submission, so you'll likely have to use javascript to pull the content out of those containers and pass them along in some fashion.
One strategy would be to add a handler to the form that fires before submit, which iterates over contenteditable containers and injects hidden form elements. The below example uses jQuery, but you could probably replicate the thought process without.
var form = $('#my_form');
var element;
$('[contenteditable=true]').each(function(){
element = $(this);
form.append($('<input/>', {
type:'hidden',
name:element.attr('id'),
value:element.html()
}));
});

Knockout and jQuery Mobile: Checkboxes

I'm trying to dynamically add checkbox and label elements to the document. Checkbox element has Knockout's data-bind attribute to bind its value to an observable value in the ViewModel. However when I try to style the checkboxes with jQuery Mobile by executing
$('input[type="checkbox"]').checkboxradio();
data-bind attributes will be removed. If I leave out the above line, data-bind attributes are properly set and the binding works.
Is there a way to have both jQuery Mobile styling and Knockout bindings at the same time?
I'm using jQuery Mobile RC1 and Knockout 1.2.1.
I have also encountered this problem. Unfortunately, all the suggestions here either did not work for me or had other issues. So I have created a simple custom binding that works in all versions of KO (including the latest v3):
ko.bindingHandlers.jqmChecked = {
init: ko.bindingHandlers.checked.init,
update: function (element, valueAccessor) {
//KO v3 and previous versions of KO handle this differently
//KO v3 does not use 'update' for 'checked' binding
if (ko.bindingHandlers.checked.update)
ko.bindingHandlers.checked.update.apply(this, arguments); //for KO < v3, delegate the call
else
ko.utils.unwrapObservable(valueAccessor()); //for KO v3, force a subscription to get further updates
if ($(element).data("mobile-checkboxradio")) //calling 'refresh' only if already enhanced by JQM
$(element).checkboxradio('refresh');
}
};
Should be used like this:
<input type="checkbox" data-bind="jqmChecked: someValue" id="checkbox1"/>
See a complete working example here:
http://jsfiddle.net/srgstm/ub6sq/
See: https://gist.github.com/1006808
Then you can do something like the following:
var $checkbox = $('input[type="checkbox"]');
$checkbox.checkboxradio();
$checkbox.dataBind({
your options..
});
Hope this'll help!
There is a problem with using knockouts default checked binding with styled objects like jQuery mobile does. It has the same issues that jQueryUi's Button/Buttonset functions. There is a label over the checkbox that indicates what is happening and it doesn't get updated properly via standard knockout checked binding.
It is discussed at http://therunningprogrammer.blogspot.com/2011/10/how-to-use-jquery-uis-button-with.html.
To use knockout directly with these styled objects from jQuery Mobile, the demonstrated code will have to be modified to handle the different DOM context. I'll post an update to the code when I can get some free time to do it.
EDIT
In Google Groups - Knockout, luv2hike posted a solution. You can see it working at http://jsfiddle.net/luv2hike/nrJBC/. Looks like a working fix for your problem.
I created a simple binding that works with jQuery Mobile 1.2.0 and Knockout 2.2.1 and works with default jQuery mobile checkboxes. This binding has no dependency on custom icons or JQuery Mobile's CSS styles. It also allows the use of regular checkbox markup in your HTML (<input type="checkbox" ... />) as opposed to using an alternate markup element like a div.
Here's the fiddle: http://jsfiddle.net/thedude458/52baX/
Note: Presently, the example only supports a single checkbox, not a list, as that is all I currently have a need for. It also assumes that the bound property is an observable.
Here is my heavily commented code on a custom handler I built for jQueryMobile checkboxes:
ko.bindingHandlers.checkbox = {
init: function(element, valueAccessor) {
// set the dom element to a checkbox and initialize it (for jquerymobile)
var checkbox = $(element);
checkbox.checkboxradio();
checkbox.attr('type', 'checkbox');
// register change event to update the model on changes to the dom
ko.utils.registerEventHandler(element, "change", function() {
valueAccessor()(
// off because it is before the ui has refreshed
$(this).siblings('label.ui-checkbox-off').length > 0
);
});
},
update: function(element, valueAccessor) {
// update the checked binding, i.e., check or uncheck the checkbox
ko.bindingHandlers.checked.update(element, valueAccessor)
// and refresh the element (for jquerymobile)
var checkbox = $(element);
checkbox.checkboxradio('refresh')
}
};

DropDownListFor does not set selected value

I have a view that is displaying a Drop down list using the HTML helper DropDownListFor
<%: Html.DropDownListFor(Function(model) model.Manufacturer, New SelectList(Model.ManufacturerList, Model.Manufacturer))%>
My controller is passing the View a ViewModel containing the Manufacturer and the ManufacturerList
Function Search(ByVal itemSrch As ItemSearchViewModel) As ActionResult
'some code mapping and model code'
Return View(itemSrch)
End Function
My ViewModel is nothing crazy just fills the ManufacturerList with a list of string values and then the Manufacturer property is just a string value containing the selected value from the drop down list.
Public Property Manufacturer As String
Public Property ManufacturerList() As List(Of String)
I'm having an issue with the view setting the selected value on the drop down list if we are reloading the Search View. I've checked the View Model (ItemSearchViewModel) when it comes into the Search function and the Manufacturer is populated with the proper selected value and successfully passes that value back to the Search View. At some point the data passed to the view doesn't seem to populate the selected value, was wondering if anyone had some ideas on why this is happening and what I can do to fix it.
Thanks
Didn't get much for answers on this so started digging into how I could fix this somewhat easily. Also in my research this seemed to be a common problem for many people with the DropDownListFor HTML Helper. I figured there had to be a way to get this working since I knew the selected value property from my ViewModel was actually getting passed to the View. So javascript and jQuery to the rescue, I ended up trying to set the selected value using the jQuery .ready function and was able to successfully get this to work. So here's my jQuery fix:
$(document).ready(function() {
$("#Manufacturer").val("<%: Model.Manufacturer %>");
});
For sake of making this easy to follow I used the full .ready syntax, or you can just use $(function () { 'code' });
If you want to solve this without using jQuery you can just use basic javascript syntax as well, it'll look something like this:
document.getElementByID("Manufacturer").Items.FindByValue("<%: Model.Manufacturer %>").Selected = true;
If you using the plain javascript call make sure to call this when the page is done loading data to the dropdownlist.
In either case all this code is doing is setting the selected value on the drop down list on the client side from the passed in Manufacturer value from the Model.
If you have any other ways to solve this problem please let me know, but this is working for me and hopefully it'll help someone else with their problem.
Thank,
I've done a similar quick-fix in JQuery today to fix this behaviour too :
$(document).ready(function() {
$(".wrapper<%: Model.Language %> option[value=<%: Model.Language %>]").attr("selected","true");
});
Though I could share it with others if needed.
I'd still like to see a real patch to this problem so many persons seems to have in a different way, maybe with an extension method of the already existing DropDownListFor Html.helper method.

Resources