How to replace button with text based on the id attribute from html to ajax - 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".

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 load Different Partial Views on the same div by radio button selection?

enter code here
*MainView.cshtml*: #RadioButtonFor(m=>m.registeras,Individual) #RadioButtonFor(m=>m.registeras,BusinessEntity) <div id="loadpartial"> </div>
I have a register form in which User can register as Individual or Business entity. I kept two radio buttons.
If user selects Individual Radio Button, then that partial view should be loaded. if user selects Business entity radio Button then second partial view should be loaded on the same div.
I am new to asp.net mvc4 razor. Can someone please give the sample code.
You will have to use jQuery in order to make ajax calls.
First reference jQuery at the bottom of your page.
in your controller, define and implement a method which returns a partial view.
[HttpGet]
public ActionResult GetRegisterForm(int registeras)
{
if(registeras == Individual)
{
return PartialView("IndividualPartialViewName");
}
else
{
return PartialView("BusinessPartialViewName");
}
}
Now in your view, you can call the above action using ajax.
<script type="text/javascript">
$(function(){
$("[name=registeras]").on('change', function(){
var $radio = $(this);
$.ajax({
url:'#Url.Action("GetRegisterForm", "ControllerName")',
data: { registeras = $radio.val() }
type: 'GET',
success: function(data){
$("#loadpartial").html(data);
}
});
});
</script>

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.

partial view not opening as jQuery UI Dialog

I need to open a partial view as dialog box on click of a button, basically add/ Edit scenario. My problem is that mu partial view does open but not as a dialog but at the bottom of the page.
Please see my code below:
I have an empty div on the page:
On the click of the button I call the below code:
function addSelectionActivate() {
var selectionID = 0;
$.ajax({
url: "AddEditSelection",
type: "POST",
data: "&selectionID=" + selectionID,
dataType: "html",
success: function (data) {
$("#addEditSelectionDialog").html(data);
$("#addEditSelectionDialog").dialog('open');
},
error: function (error) {
alert(error.status);
}
});
}
My controller has a method "AddEditSelection" which returns the result. But the partial view opens at the end of the page rather than as a dialog. Please help what I might b edoing wrong.
you need to add the partial in a seperate div contained in the dialog div.
eg:
<div id="DialogDiv">
<div id="AnotherDiv">
</div>
</div>
and register "DialogDiv" as dialog and load ur partial in the "AnotherDiv"

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