Custom grid button to load ajax content depending on selected row - jqgrid

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.

Related

Ajax modal popup with modal binding from within partial view

I am trying to find a solution for a while but could not find one... I have partial view which is bound to a modal and it displays data in grid. Something like below
#model abc
#Html.Grid(Model)
{
grid columns
column with edit link
}
on the click of edit link from a grid, through ajax, I would want to display popup window in partial view which is bound to another model. This bootstrap popup window should also be bound through model binding as I need to perform server side validations when click on Submit of popup
#model pqr
<div>
popup window with grid columns displayed in form for editing.
</div>
Any help with sample code would help tremendously.
There are probably other ways to do this but I have done like this before:
Your edit link must have id as the id to be passed as param to Controller
Get data and pass the model to the partial view with properties populated
$(".YourEditLinkClass").click(function () {
var id = $(this).attr('id');
$.ajax({
url: "#Url.Action("GetDataForPopUpWindow", "YourController")",
type: "GET",
dataType: "html",
data: { id: id },
success: function (data) {
$("#modal_" + id).html(data);//target position of modal
$('#pqr_' + id).modal('toggle');
}
});
});
Controller code:
public ActionResult GetDataForPopUpWindow(int id)
{
using (YourDBContext)
{
var data = YourData;
pqr pqrModel = new pqr();
pqrModel.YourModelProperty = data.CorrespondingProperty;
return PartialView("_GridPartialView", pqrModel);
}
}
Your bootstrap modal must have the id as id="pqr_#Model.Id" in the partial view called _GridPartialView. Hope it makes sense.

How to replace button with text based on the id attribute from html to ajax

I have many products and each products have buttons with different attribute IDs. On click of that button, the attribute of the button is passed to ajax function and I am able to get different attribute ID when I give them in alert message.
Now I want to replace the button with a text based on that attribute ID.
html code:
<button bookid='".$row['bookid']."' id='book' type='button'>Add</button>
My ajax code is:
$("body").delegate("#book","click",function(event){
event.preventDefault();
var bid = $(this).attr('bookid');
$.ajax({
url : "login_action.php",
method : "POST",
data : {addToStore:1,bookid:bid},
success : function(msg){
if(msg == 0){
alert('Already 1 product is added ');
}else{
$(bid).text('Added');
}
}
})
})
The problem is I am not able to replace the button with the text "Added".

How to pass javascript variable to velocity template

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.

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.

MVC 3 Reload current page with modified querystring values

Background:
I have an MVC layout (master) view which uses #Html.RenderAction to display a dropdown in the left side navigation panel. This dropdown will be displayed on all the pages of the site.
The dropdown is wrapped in a form element and on change of the dropdown the form is posted.
Question:
Now, once the form is posted, I need to reload the contents of the current page (whatever page the user is currently on...) with the value of the dropdown attached in the querystring. This would mean replacing the value which might already be there in the querystring from a previous selection.
Example:
The user navigates to the Home page of the website:
Url: /Home/?dropdownvalue=blue
At this point the dropdown displays 'Blue' as selected. The user changes the value in the dropdown to 'Red'. I need to reload the page with the following url -
/Home/?dropdownvalue=red
The user moves to another page in the site:
Url: /CustomerFavorite/?dropdown=red
Change the value in the dropdown from 'Red' to 'Green'.
The 'CustomerFavourite' page should be reloaded with 'Green' in querystring.
I apologize for the lenghty post. But, thought of providing some extra information to clarify the issue.
Thanks.
Thanks to Darin for providing the link for javascript manipulation of the querystring. But, I wanted a server side solution so here's how I implemented it -
public ActionResult _ColorSelection(ColorModel model)
{
string selectedColor = model.Color.Value;
// Modify Querystring params...
NameValueCollection querystring =
HttpUtility.ParseQueryString(Request.UrlReferrer.Query); // Parse QS
// If Querystring contains the 'color' param, then set it to selected value
if (!string.IsNullOrEmpty(querystring["color"]))
{
querystring["color"] = selectedColor;
}
else // Add color key to querystring
{
querystring.Add("color", selectedColor);
}
// Create new url
string url = Request.UrlReferrer.AbsolutePath
+ "?" + querystring.ToString();
return Redirect(url); // redirect
}
You may try using a GET method of the form in which the drop down is wrapped:
#using (Html.BeginForm(null, null, FormMethod.Get))
{
#Html.Action("SomeActionThatRendersTheDropDown", "SomeController")
}
or maybe the entire form is wrapped inside the action:
#Html.Action("SomeAction", "SomeController")
and then in javascript subscribe to the change event of the dropdown and trigger the submission of the form:
$(function() {
$('#DropDownId').change(function() {
$(this).closest('form').submit();
});
});
Because you have used GET request, this will automatically reload the current page sending the value of the dropdown in the query string.
If you are using jQuery you can create a function that will post the selected value in your list.
$(document).ready(function () {
$("#ListId").change(function () {
$.ajax({
url: "CustomerFavorite/Edit",
type: "POST",
data: "colour=" + $("#ListId").val(),
success: function (result) {
//Code to update your page
}
},
error: function () {
}
}

Resources