Keep current Jquery accordion pane open after postback - c#

its me again.
this time i am trying to keep the current JQuery accordion pane open after postback. I have followed the example here: Keep the current jQuery accordion pane open after ASP.NET postback? in addition to couple others i have seen around. i still cannot get it to work, the only difference with mine is that i am formulating the script through my code behind and pushing to the client.
this is what i have:
public static string getAccordionContainerScript(string container)
{
return #"$(document).ready(function() { var activeIndex = parseInt($('#<%=accordionActiveIndex.ClientID %>').val()); $(" + '"' + '#' + container + '"' + ").accordion({collapsible: true, heightStyle: \"content\", navigation: true,change: function (event, ui) { var index = $(this).accordion(\"option\", \"active\");$('#<%=accordionActiveIndex.ClientID %>').val(index);} }).show(); })";
}
my reason for doin this is due to the fact that i am re-using code blocks as i have several of the same controls throughout the application.
also, when i use the markup display expression (<%= =>), it throws a client error and my other client controls do not work such as my modal, etc.
client error is: Uncaught Error: Syntax error, unrecognized expression: #<%=accordionActiveIndex.ClientID %>
what could i be doing wrong?

You are doing wrong exactly what the error message says:
You are sending to the Response the string <%=accordionActiveIndex.ClientID %>. That string must be processed by the WebForms engine, so it must be in the aspx page. The browser doesn't know how to deal with that code, and that's why the browser is throwing that error.
I'm afraid that you need the accordionActiveIndex.ClientID value passed to that function, so you can do something like this (note the new parameter, and also, ignore the line breaks in the string. I've added for legibility):
public static string getAccordionContainerScript(string container, string clientId)
{
return string.Format(#"$(document).ready(function() { var activeIndex = parseInt($('#<%=accordionActiveIndex.ClientID %>').val());
$(" + '"' + '#' + container + '"' + ").accordion({collapsible: true, heightStyle: \"content\", navigation: true,change: function (event, ui) { var index = $(this).accordion(\"option\", \"active\");
// pay attention here
$('#{0}').val(index);} }).show(); }), clientId);
}

Related

Why I obtain a SyntaxError: expected expression, got '<) tryng to perform a redirection clicking a button into a SharePoint webpart?

I am pretty new in SharePoint (I am working on SharePoint 2013) and .NET and I have the following problem.
Into a Web Part I have a button and I have to insert a JavaScript redirect using the OnClientClick property. In my code I have done something like this:
ImageButton btnApplica = new ImageButton();
btnApplica.ToolTip = "Documento in Entrata";
//btnApplica.Click += btnApplica_Click_Scelta_Campi_Etichetta;
btnApplica.OnClientClick = "<script>"
+ "function() {"
+ "window.location.href = '" + SPContext.Current.Web.Url + "/MYPROJECTNAME WEBPART/Carica documento.aspx?mode=scelta_campi_facoltativi_etichetta&obj='" +obj
+ ";return false;"
+ "}"
+ "</script>";
//btnApplica.Click += btnApplica_Click;
//openButton.OnClientClick = "return false;";
btnApplica.ID = "btnEntrata";
btnApplica.ImageUrl = "/_layouts/15/images/myprojectname/Default/Ribbon/DocEntrataRibbon.png";
LinkButton text = new LinkButton();
text.Text = "Documento in Entrata";
text.ID = "btnEntrataTxt";
text.Width = 80;
//text.Click += btnApplica_Click;
//text.Click += btnApplica_Click_Scelta_Campi_Etichetta;
buttondiv.Controls.Add(btnApplica);
buttondiv.Controls.Add(new LiteralControl("<br/>"));
buttondiv.Controls.Add(text);
ribbondiv.Controls.Add(buttondiv);
As you can see, I am trying to create an "in client" redirection so I used the OnClientClick property on this button. I defined a simple JavaScript function to perform the rediration that end with the return false to avoid that the entire page is reloaded after the button click, this:
btnApplica.OnClientClick = "<script>"
+ "function() {"
+ "window.location.href = '" + SPContext.Current.Web.Url + "/MYPROJECTNAME WEBPART/Carica documento.aspx?mode=scelta_campi_facoltativi_etichetta&obj='" +obj
+ ";return false;"
+ "}"
+ "</script>";
This code section have some problem, clicking on my button it happens that:
The HTTP POST request is performed to the correct URL:
http://mymachine:8080/Protocollo/pg/MYPROJECTNAME WEBPART/Carica documento.aspx?mode=ant&obj=17&IsDlg=1
(I see it by the Network tab in Firefox, it seems to me absolutly correct)
But the page is entirely refreshed (so I don't obtain the section replacement that I expect).
Looking into the JavaScrip browser console I obtain this error message:
SyntaxError: expected expression, got '<'
So I think that something went wrong defining the second statment of my simple JavaScript function (the return false).
I am doing:
+ ";return false;"
because I am appending the ; symbol to say that the previous statment is complete (the window.location.href=.... that performs the redirection) and it is follwed by the return false.
I am going crazy and I can't understand what is wrong...maybe some symbol or missed escape.
What is wrong? What am I missing? How can I fix this issue?
I think error can be when you are using <script> tags in OnClientClick value.
Write like this:
btnApplica.OnClientClick = "var ClickMySuperButton = function() {"
+ "window.location.href = '" + SPContext.Current.Web.Url + "/MYPROJECTNAME WEBPART/Carica documento.aspx?mode=scelta_campi_facoltativi_etichetta&obj='" +obj
+ ";return false;"
+ "}; ClickMySuperButton();";
or add your script somewhere on ascx page:
function ClickMySuperButton(){
};
and use in code-behind like this:
btnApplica.OnClientClick = "ClickMySuperButton();";

Textbox (and other controls) - "Object not set to an instance...."

I realize this is a common error and I've followed the many fixes to this problem offered online but have yet to find a solution.
I developed a winform app which gets JSON from an external website. I click a button control and the app goes through my json serialiser method and posts the results to a textbox and appends to a textarea.
public void RenderData(string buttonText)
{
if (buttonText == "Start")
{
EquationData deserializedData = getData("http://test.ethorstat.com/test.ashx");
var processed = new ProcessEquation();
int result = processed.Calculate(deserializedData);
string res = deserializedData.parm1 + " " + deserializedData.op + " " + deserializedData.parm2 +
" = " + result;
TextBoxResult.Text = res;
equation.Append(" " + deserializedData.parm1 + " " + deserializedData.op + " " + deserializedData.parm2 +
" = " + result + '\n');
TextAreaResults.Value = equation.ToString();
}
}
This worked fine as it was. But requirements have changed in that the app has to poll data every second. Therefore I created a wcf web service called by a jquery script to run every second.
The problem is my controls - textbox and textboxarea - generate {"Object reference not set to an instance of an object."}. My assumption is that these controls aren't being loaded now that I'm calling the method from JQuery's ajax function (?).
$(document).ready(function () {
//while ($('#eThorButton').text != "Stop") {
if ($('#eThorButton').click) {
$.ajax({
url: 'Service/eThorService.svc/getUpdate',
method: 'get',
dataType: 'json',
success: function(){
alert("success");
},
error: function (err) {
alert(err);
}
})
//delay(1000);
}
});
My controls do show in intellisense and, of course, on Default.aspx when I run it. How can I fix this?
EDIT
I solved the 'Object not set...' problem by instantiating a new textbox:
public partial class _Default : Page
{
public static StringBuilder equation = new StringBuilder();
public TextBox TextBoxTest = new TextBox();
When I debug and step through the value is set, the textbox renders but the textbox is empty. How do I fix that?
Make your method static and add annotation [WebMethod] and return list of results.
[System.Web.Services.WebMethod(EnableSession=true)]
public static List<string> RenderData(string buttonText)
{
// return result here
}
Pass parameter with data:{buttonText:yourvalue} to $.ajax call. and change the success function and assign values to your control on client side via javascript.
success : function(msg){
if(msg.d!=null){
$('#<%=TextBoxResult.ClientID%>').val(msg.d[0]);
}
}

AddItem to shopping cart

I'm building a webshop in C# (MVC). Now I want to change the number of items that is shown in the cart-icon (at the layout-page). I've found this code and want to customize it to my page.
$(function () {
// Document.ready -> link up remove event handler
$("##product.ArtNumber").click(function () {
// Get the id from the link
var itemToAdd = $(this).attr("data-id");
if (itemToAdd != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
Now I have a question about " $.post("/ShoppingCart/RemoveFromCart" "
In my case I don't want to switch to another page when you click the button - but add an item to the cart (at the layout-page). What can I write instead of "post"? As I've understand this is used when you want to open a new HTML-page?
The $.post is shorthand of jQuery.post. http://api.jquery.com/jquery.post/
It is an ajax call, and occurs in the background asynchronously. You are expected to have an endpoint that will handle the HTTP post on the server. Ideally this will update the server with the cart information such that it is available later if the client disconnects or closes their browser.
In my case I don't want to switch to another page when you click the button
I failed to actually answer your question directly. It will not take you to a different page or navigate away from the current page. You can actually open a new tab and paste that URL into the browser and see that it returns JSON.

Using PagedList in partial views in MVC 4 is throwing off jQuery/JS when navigating 'paged' pages

I've just implemented paging using PagedList in my MVC 4 application. The homepage of my app contains a partial view that displays a list of summarised data about certain objects. Beside each list item is a button that when clicked launches a modal window, displaying more information about that particular list item.
All works well on the first 'paged' page of list items, however if I navigate to the second 'paged' page and click the button to launch modal nothing happens. From developer tools in Chrome I get Uncaught TypeError: Object [object Object] has no method 'modal'.
The partial in question outputs the list, contains the DIV for the modal and a JS function to handle the button click event that launches modal windows. Here's the JS from that partial view:
<script type="text/javascript">
$(document).ready(function () {
$('.show-modal').click(function () {
var url = $('#modal-view-property-from-get-all').attr('data-url');
var id = $(this).attr('data-id');
$.get(url + '/' + id, function (data) {
$('#view-property-from-get-all-container').html(data);
$('#modal-view-property-from-get-all').modal('show');
});
});
});
</script>
When I navigate back to the first 'paged' page, the button doesn't fire either and same uncaught typeError is thrown. Another jQuery plugin I use that truncates multi-line text also stops working and text overflows its containing DIV.
What's actually happening here - why does using paging interfere with JS like this?
How can I resolve this?
EDIT:
All records of particular type are returned from controller action:
return PartialView("_GetAllPropertiesPartial", model.ToPagedList(pageNumber, pageSize));
Since it's a partial, paging navigation is handled by Ajax.ActionLinks():
#Ajax.ActionLink("<<", "GetAllProperties", new { page = 1 }, new AjaxOptions { UpdateTargetId = "quick-property-search-results" })
You need to bind the event handler to something that doesn't get replaced in your markup, and use the .on() method rather than .click(), like so:
<script>
$(function () {
$('body').on('click', '.show-modal', function (e) {
var url = $('#modal-view-property-from-get-all').attr('data-url');
var id = $(this).attr('data-id');
$.get(url + '/' + id, function (data) {
$('#view-property-from-get-all-container').html(data);
$('#modal-view-property-from-get-all').modal('show');
});
});
});
</script>
You can use something other than body if you have a parent element that you know won't get replaced. It's also worth noting that you could be using .load(): http://api.jquery.com/load/
$('#view-property-from-get-all-container').load(url + '/' + id, function (response, status, jqxhr) {
// this is an optional callback
$('#modal-view-property-from-get-all').modal('show');
});

jquery autocomplete source as a url that takes in query strings

I am trying to use the jQuery Autocomplete UI widget on a text box and I am having no luck getting the source to work. I have a database full of names that I want the autocomplete to work against, so I created a page called searchpreload.aspx and it looks for a variable in the url and queries the db based on the querystring vraiable.
When I type in the search box, I am using the keyup function so I can capture what the value is that needs to be sent over. Then I do my string gathering from the db:
if (Request.QueryString["val"] != null)
{
curVal = Request.QueryString["val"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
It queries the database correctly and then it takes the strings and puts them in a list and prints them out to the page:
private void PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\n");
}
}
Response.Write(sb.ToString());
}
}
This works fine, if I navigate to this page I get a listing of all of the data that I need, however I can not get it to show up in the autocomplete box. When I debug the code, the source of the autocomplete is calling this page correctly each time and getting the correct data, it just is not displaying anything. Am I doing something wrong?
JQuery Code:
<script type="text/javascript">
$(document).ready(function () {
$(".searchBox").focus();
var checked = 'rbCNumber';
$("input:radio").change(function (eventObject) {
checked = $(this).val();
});
$(".searchBox").keyup(function () {
var searchValue = $(".searchBox").val();
//alert("Searchpreload.aspx?val=" + searchValue + "&Type=" + checked);
$(".searchBox").autocomplete({
source:"Searchpreload.aspx?val=" + searchValue + "&Type=" + checked,
minLength: 2
});
});
});
</script>
Also, should I be doing this a different way to make it faster?
You arent displaying the results into anything - source will return a data item that you can then use to populate something else on the page. Look at autocomplete's select and focus methods.
here is an example of how i have done it:
field.autocomplete({
minLength: 1,
source: "whatever",
focus: function (event, ui) {
field.val(ui.item.Id);
return false;
},
search: function (event, ui) {
addBtn.hide();
},
select: function (event, ui) {
setup(ui);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.Id+ ", " + item.Name + "</a>")
.appendTo(ul);
};
The .data part is the part you are missing. Once the data comes back from the autocomplete you arent doing anything with it.
The source does not need to include the term the user entered into the search box. Jquery will automatically append the term onto the query string for you. If you watch the request get generated in firebug, you will see the term query hanging off the end of the url.

Categories

Resources