How to pass javascript variable to velocity template - spring

I created a dropdownlist using jqwidgets and i got a form using velocity template. In the form action i want to get the selected value of my dropdownlist. i need the value in my controller page. How can i get the selected value of the dropdownlist inside velocity template variable? I am passing the item inside $submitUrl.setParameter("filePath", "item"). but if I print the value inside controller then I am getting only item. not the selected value of the dropdownlist. Any suggession?
<script type="text/javascript">
$(document).ready(function ()
{
// Create the countryjqxWidget DropDownList
$("#countryjqxWidget").jqxDropDownList({source: countryList, selectedIndex: 0, width: '200', height: '25', theme: 'ui-redmond'});
$('#countryjqxWidget').on('change', function (event)
{
var args = event.args;
if (args) {
// index represents the item's index.
var index = args.index;
var item = args.item;
// get item's label and value.
var label = item.label;
var value = item.value;
alert(value);
var item = $("#jqxDropDownList").jqxDropDownList('getSelectedItem');
}
});
});
</script>
<form id="form" class="form-horizontal" action="$submitUrl" method="post" >
#lr_btn("submit-btn", "Submit", "Submitting...")
</form>
#set( $submitUrl = $renderResponse.createActionURL() )
$submitUrl.setParameter("submit", "upload")
$submitUrl.setParameter("filePath", "item")

Have you tried by adding the "countryjqxWidget" within your Form and setting its "name" attribute. As far as I know, if you set the "name" attribute, the selected value will be passed automatically on Form submit. It does not matter that the jQWidgets DropDownList is created from DIV tag, You can still set its "name" attribute.

Related

Kendo MVVM Dropdown - How to set initial value based on other data?

I have the following html for a Kendo MVVM DropDownList:
<select id="responseTypeDDL"
data-role="dropdownlist"
data-text-field="SystemResponseTypeCode"
data-value-field="SystemResponseTypeId"
data-bind="value: selectedSystemResponseTypeCode, source: responseTypes">
</select>
This is my view model:
SC.ViewModels.Reference.ResponseTypeDataSource.read();
var responseTypeDDL = kendo.observable({
responseTypes: SC.ViewModels.Reference.ResponseTypeDataSource,
selectedSystemResponseTypeCode: null,
setSelectedSystemResponseTypeCode: function (code) {
this.selectedSystemResponseTypeCode = code;
},
});
kendo.bind($("#responseTypeDDL"), responseTypeDDL);
// after reading data, I call the method to set the selected value like this:
self.ResponseTypeDDL.setSelectedSystemResponseTypeCode(results.code);
The ResponseTypeDataSource.read() method returns a list of "XML", "JSON". This is the SystemResponseTypeCode field. I also read another data item from the database
and check its response type. Let's say it is "JSON". How do I set the drop down to have "JSON" selected?
First of all this part seems to be wrong
setSelectedSystemResponseTypeCode: function (code) {
this.selectedSystemResponseTypeCode = code;
},
You should make sure to call set() method while modifying an observed variable, otherwise it might not update the bindings:
this.set("selectedSystemResponseTypeCode", code);
And for your actual question
You need to set data-value-primitive="true" in order to work with just the id (Kendo Docs) (Please note changes below, value: selectedSystemResponseTypeId)
<select id="responseTypeDDL"
data-role="dropdownlist"
data-text-field="SystemResponseTypeCode"
data-value-field="SystemResponseTypeId"
data-value-primitive="true"
data-bind="value: selectedSystemResponseTypeId, source: responseTypes">
</select>
SC.ViewModels.Reference.ResponseTypeDataSource.read();
var responseTypeDDL = kendo.observable({
responseTypes: SC.ViewModels.Reference.ResponseTypeDataSource,
selectedSystemResponseTypeCode: null,
selectedSystemResponseTypeId: null,
setSelectedSystemResponseTypeId: function (id) {
this.set("selectedSystemResponseTypeId", id);
},
});
kendo.bind($("#responseTypeDDL"), responseTypeDDL);
// Get your id
var id = ...
responseTypeDDL.setSelectedSystemResponseTypeId(id);
Working example: http://dojo.telerik.com/AbIm/8
I've managed to manually set the value in dropdownlist without resorting to
data-value-primitive="true"
because i need to access the selected value and display other fields.
Here's the solution:
var id = 1004;
var dataItem = responseTypeDDL.responseTypes.get(id); //get the id in your datasource
responseTypeDDL.set("selectedsystemResponse", dataItem);

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?
My main page has a DropDownList (DropDownListFor) and a partial view which ONLY contains a list of "items". The items shown in this partial view are dependent upon the item selected in the DropDownList. There's a 1 to many relationship between the DropDownList item and the items in the partial view. So, when the user changes the value of the DropDownList, the content in the partial view will dynamically change to reflect the item selected in the DropDownList.
Here's my DropDownList:
<div data-role="fieldcontain">
Choose Capsule:<br />
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules" })
<br />
</div>
Here's my Partial View declaration on the same page:
<div data-role="fieldcontain">
#Html.Partial("_FillerPartial", Model.Fillers)
</div>
I'm not very familiar with Ajax, but looking at other examples, here's what I have for my Ajax:
$(document).ready(function () {
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
alert("server returned: " + data);
}
});
});
});
And finally, here's a screenshot of what's going on. By changing the "Choose Capsule" drop down list, I want the Filler list to update dynamically:
You can load the drop down list as a partial view from the controller using ajax.
The controller code:
[HttpGet]
public virtual ActionResult GetFillersByCapsule(string cappk)
{
var model = //Method to get capsules by pk, this returns a ViewModel that is used to render the filtered list.
return PartialView("PartialViewName", model);
}
The main view html:
<div id="filteredList">
</div >
The partial view
#model IEnumerable<MyCapsuleModel>
foreach (var x in Model)
{
//Render the appropriate filtered list html.
}
And you can load the filtered list using ajax:
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
$("#filteredList").empty();
$("#filteredList").html(data);
}
});
});
Hope this helps.
You can't update the partial, per se, because the partial will never be rendered again without a page reload. Once you receive the HTML, ASP is done, you're on your own at that point.
What you can do, of course, is switch out the content of a particular div or whatever using JavaScript. Your example in particular screams Knockout, so that's what I would recommend using.
Change your HTML to add a data-bind to your containing div:
<div data-role="fieldcontain" data-bind="foreach: filler">
<button data-bind="text: name"></button>
</div>
And your DropDownList:
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules", data_bind = "event: { change: updateFillers }" })
Then, some JavaScript:
var FillersViewModel = function () {
var self = this;
self.fillers = ko.observableArray([]);
self.updateFillers = function () {
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
self.fillers(data.fillers) // where `fillers` is an array
}
});
}
}
var viewModel = new FillersViewModel();
ko.applyBindings(viewModel);
This is a very simplistic example, and you'll need to do some more work to make it do everything you need it to do in your scenario, but the general idea is that every time the dropdown list is changed, Knockout will call your updateFillers method, which will execute the AJAX and put new data into the fillers observable array. Knockout automatically tracks changes to this array (hence the "observable" part), so an update is automatically triggered to any part of your page that relies on it. In this scenario, that's your div containing the buttons. The foreach binding will repeat the HTML inside for each member of the array. I've used a simple button element here just to illustrate, but you would include the full HTML required to create your particular button like interface. The text binding will drop the content of name in between the opening and closing tag. Refer to: http://knockoutjs.com/documentation/introduction.html for all the binding options you have.
There's much more you could do with this. You could implement templates instead of hard-coding your HTML to be repeated in the foreach. And, you can use your partial view to control the HTML for this template. The important part is that Knockout takes the pain out of generating all this repeating HTML for you, which is why I recommend using it.
Hope that's enough to get you started.

Custom grid button to load ajax content depending on selected row

I need to make a custom buttom in my grid that will open a modal which will render a select field with options depending on selected row.
So the user will select a row and click the button. The row id should be passed as an url parameter to my action so that it can make a query and populate the select field.
This is where I'm struggling:
navigatorExtraButtons="{
honorarios:{
title: 'Consultar honorários do processo',
caption: 'H',
icon: 'none',
onclick: function(){
var id = jQuery('#processoTable').jqGrid('getGridParam','selrow');
if (id) {
var ret = jQuery('#processoTable').jqGrid('getRowData',id);
// need to pass ret.nrProcesso as param to the URL that will load content into the modal
} else { alert('Please select a row.');}
}
},
With above code I can get the desired ID value from selected row. But I don't know how to assign it to a
<s:url... param
and populate a modal...
Thanks in advance.
I've found a solution. Posting here hoping it might help someone else.
I've ended up using plain old jquery script to get the modal to show up instead of jquery-plugin.
Just construct your action url adding desired parameter and call an ajax function:
<sj:submit id="consulta_honorarios" value="Consultar Honorários" onClickTopics="honorarios" button="true"/>
<sj:dialog
id="mydialog"
title="Consultar honorários"
autoOpen="false"
modal="true"
dialogClass="ui-jqdialog"
/>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#consulta_honorarios").click(function(){
var actionURL = '<s:property value="%{advprocselecturl}" />';
var id = jQuery('#processoTable').jqGrid('getGridParam','selrow');
if (id) {
var ret = jQuery('#processoTable').jqGrid('getRowData',id);
actionURL += '?nrProcesso=' + ret.nrProcesso;
// alert('id='+ret.nrProcesso+' / actionURL='+actionURL);
jQuery.ajax({
url: actionURL
}).done(function(data){
jQuery('#mydialog').html(data).dialog('open');
});
} else {
jQuery('<div />').html('Por favor, selecione um registro.').dialog();
}
});
});
In your action you must declare a variable with the same name as your url parameter (nrProcesso in my case) with respective getter and setter.

MVC3 Razor conditional loading

I want to implement following:
A combobox/DropDownListFor named "target" in a view. It contains (e.g.) A and B as choice.
In the same view I have another combobox named "medium". Its content depends on the chosen target, e.g.:
- if target = "A", combobox "medium" will show 1 and 2 as choice.
- if target = "B", combobox "medium" will show 3 and 4 as choice.
I have implemented combobox "target" successfully, but I don't know how to implement combobox "medium" related to "target". If I am not wrong, the logic should be: get the chosen targetid -> find all medium related to the targetid -> fill combobox "medium" with the result.
Here is snippet of my current view (combobox "target"):
<div class="editor-label">
#Html.LabelFor(model => model.TargetId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.TargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.TargetId))
</div>
Thx in advance.
You could use the javascript OnChange of the first drop to do an ajax call to obtain the values based from the choice A or B.
Then with the JSon response you get from the controller you fill the dropdown "Medium"
in the JS file do something like this:
$(document).ready(function () {
$("#target").change(function () { GetMediumValues("#target", "#medium"); });
});
function ClearDrop(objSource) {
$(objSource).empty();
}
function GetMediumValues(objSource, objDest) {
var url = '/mySite/GetMediumValues/';
$.getJSON(url, { id: $(objSource).val() }, function (data) {
ClearDrop(objDest);
$.each(data, function (index, optionData) {
$(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
While in the controller
public ActionResult GetMediumValues(string id)
{
int myId = 0;
int.TryParse(id, out myId);
var select = new SelectList(repository.GetMediumValues(myId), "Id", "Name");
return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}

SelectedValue on html drop down list in MVC

I am new to MVC, so sorry if I am being a bit thick. I am using VB
I am trying to fill an html drop down list using data from a db, but the first item is always selected, no matter what.
What am I doing wrong?
Here is my code - In the controller:
ViewData("MatchTypeList") = New SelectList(_db.GetMatchTypes.ToList(), "MatchTypeID", "MatchTypeName", SelectedValue)
And in the view
<%= Html.DropDownList("MatchType", CType(ViewData("MatchTypeList"), IEnumerable(Of SelectListItem)), "Any", New With {.class = "forminput"})%>
This is a problem with mvc. One work around would be to change the name of the dropdownlist to anything but the name of the property. Then, before submitting to change the name back to the true name of the property.
An example:
<script type="text/javascript">
$(function () {
$("form").submit(function () {
$("select").each(
function () {
$(this).attr("name", $(this).attr("name").replace(/ZZZ/, ''));
});
});
});
</script>
<%= Html.DropDownList("MatchTypeZZZ", CType(ViewData("MatchTypeList"), IEnumerable(Of SelectListItem)), "Any", New With {.class = "forminput"})%>
I place the javascript (it uses JQuery) in my master page so any form in the app that has a dropdownlist can safely have its name appended with ZZZ and then set back to its original name on submission.

Resources