Category Archives: Literal

Literal

[RESOLVED]Newbie intern: A little lost on how to structure and get my project started (updating DB tables with an SPA)

Hi all,

So here are the details of the project that I have been assigned:

The company has several database tables which I am to make accessible via a webpage, and users that are properly authenticated should be able to go in, select the appropriate table from a drop-down and then edit the relevant row. The updates should then
be send back to the database. They already have a web project going that uses Web-Api as a backend with angular.js as a front-end, and I’d like to make mine as compatible as that so that it could eventually be integrated within. 

Initially, I thought to use strongly typed models using the ado.net data object model, but what if they want to dynamically add a new table to the list in the drop down? Would I not have to go into my code, and always explicitly add a new model to accommodate
this? Is there a way to dynamically handle any new table (perhaps by not using Entity Framework)?

If you need more details, just let me know. How would you more experienced programmers handle this?

Thanks in advance, any advice would be appreciated! :)

ZimbuTheMonkey

t what if they want to dynamically add a new table to the list in the drop down?

use DataTable. Or use plugin architecture and add dll’s to the project.

What you need is some kind of meta data driven approach, where you dynamically get the tables and their columns from the database and allow user to update them. Please see this example which is done for WPF. You can easily adopt for a web application

Dynamic Data Entry With XML Literals

Thank you, I’ll have a look.

[RESOLVED]Razor syntax with Google maps API Javascript error?

In my MVC4 web application, i’m passing the values from controller to the razor view.Values passing properly.Issue i’m facing is in my Google maps javascript section i can’t put razor values with javascript.Actually i’m passing Controller’s values to a Javascript
array.Following is the code section which gives me an error.

var locations = [@foreach (var item in Model){ 
['modelItem => item.locationname','@modelItem => item.latitude','@modelItem => item.longtitude'],
}];

Don’t you just mean this?

var locations = [@foreach (var item in Model){ 
['@item.locationname','@item.latitude','@item.longtitude'],
}];

I tried this way also.It’s not working.

Define "not working".  Do you get compile errors?  Runtime errors?  If you look at the page source is the javascript being rendered as you would expect?  Is it the javascript that isn’t working rather than the razor code?

I’m getting a compilation error.Following is the error.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS1012: Too many characters in character literal

Source Error:


Line 15: 
Line 16:             var locations = [@foreach (var item in Model){ 
Line 17:                                  ['@item.hospital_name','@item.latitude','@item.longtitude'],
Line 18:                              }];

var locations = [@foreach (var item in Model){
                <text>@Html.Raw(string.Format("['{0}','{1}','{2}'],", item.hospital_name, item.latitude, item.longtitude))</text>
    }];

this is probably simpler though

var locations = [@foreach (var item in Model){
                <text>['@item.hospital_name','@item.latitude','@item.longtitude'],</text>
    }];

 use @html.raw(json.encode())  method to access model properties in javascript

var locations = [@foreach (var item in Model){ 
var itemjson=@Html.Raw(Json.Encode(item )
['modelItem =>itemjson.locationname','@modelItem =>itemjson.latitude','@modelItem =>itemjson.longtitude'], }];

Great!! It works now.I saw this <text> tag thing on internet when i’m searching this on internet.But didn’t found a proper example how to use it.So from this i could easily solve the issue.Thank you.

Wow this is also a great solution.Thank you too.I marked your reply also as an answer.I want to clarify something.Why should i use json here?Because i don’t want to pass the values elsewhere.Just need to add the values to a javascript array.Bit confused
on that.But i know this is also a solution because when i’m checking on this issue prior to post it here i saw these type of solutions too.

You would use json if you were manipulating the property values via javascript and wanted to set a javascript variable to contain a json object that represents your .net object.  You aren’t building this array via client-side js though so you don’t need
to, and the posted example doesn’t work anyway if you try it.

OK thanks.And i did the way that you had mentioned.Although the errors went,now map is not loading in the browser.I tried with @modelItem => item.locationname name instead of @item.locationname.Then again gives the previous error.Values are coming from the
controller to the view.I checked that by putting @Html.DisplayFor(modelItem => item.locationname).So there’s a javascript issue.

Why are you using @modelItem=>item.locationname?  It isn’t required, just use @item.locationname.  "=>" is a lambda expression and is used by functions that accept them such as Html.DisplayFor.  When you’re building your js array you’re not using helpers,
just writing raw html to the stream.

If the map isn’t loading in the browser you’ll need to diagnose that as a separate issue.  Try using a hard-coded array just to get your maps working as that will eliminate any change that it is your razor code giving you problems.  Once you have the code
working with a hard-coded array, look to generate that array from your data using the razor syntax.

OK.Thanks for the explanation :)

Hi,i checked the source code of the webpage.Locations are loading properly into javascript.So the confusing thing is same code is working on PHP.I checked it.Exact same code.HTML,JS all are same.But in ASP not showing it.Why is that?I’m bit confused here.Is
there anything else to do in ASP when loading javascript?I’m new to MVC4 and Razor syntaxes that’s why i’m asking :)

Server technology makes no difference to client-side technology.  There will be a difference somewhere you just haven’t spotted.

Yeah i know that.But i was thought is there any specific way to load javascript in MVC4 with Razor.OK then i’ll check it again thoroughly.

[RESOLVED]what is Json.Encode() usaged in mvc

when we call any server side function through jquery ajax and when server side function return data then data is serialize automatically in json format….so why we need to use

Json.Encode(ViewBag.Faculties)

 

//Get all faculties with the help of model
// (ViewBag.Faculties), and convert data into json format.
var allFaculties = @Html.Raw(Json.Encode(ViewBag.Faculties));

 
i never work with mvc but i worked with webform for long time and have seen that when we call server side function by jquery ajax then i always get result in json format by default.
 
in mvc data is not serialize in json format automatically ?
 
if action method return json result set then what happen? do we need to use Json.Encode() in case when action method return type is json resultset ??
 
please share your knowledge. thanks

mou_inn

var allFaculties = @Html.Raw(Json.Encode(ViewBag.Faculties));

I believe the above code is written in the javascript. You are trying to generate javascript code in the view. In this javascript code you are setting the JSON. As you are generating the javascript code, you need to convert your object (ViewBag.Faculties)
to string. This where you need to use the Json.Encode

mou_inn

if action method return json result set then what happen? do we need to use Json.Encode() in case when action method return type is json resultset ??

If your action method is returning a json object, then you don’t need to convert the object to string using the Json.Encode.

Converts the json object to text.

From MSDN: http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111).aspx

Call the Encode method to convert a data object (for example, a set of data records that you return from a database query) to a string that is encoded in JSON format. You typically convert data objects to JSON format in order to work with the data as text
in a web page by using JavaScript. This lets you create a page where users interact with the data in the browser without requiring round trips to the server.

Hi mou_inn,

First, for Json.Encode is used to convert Object to string, so, if you need the JSON string, you could use it, if you just need the JSON Object, you don’t need convert to string.

mou_inn

if action method return json result set then what happen? do we need to use Json.Encode() in case when action method return type is json resultset ??

That’s base on your requirement, if you want to get the JSON string, you need to convert object to string.

On the other hand, there are the corresponding function in jQuery.

Best Regards

Starain

what Html.Raw() does ?

Hi mou_inn,

That is used to encode the data to HTML.

@Html.Raw("<div>value</div>")

Best Regards

Starain

mou_inn

what Html.Raw() does ?

Html.Raw does not encode the Html. It generates the string as it is. Other Html helpers encodes the Html to prevent security attacks. You need to be careful if you are using Html.Raw.

programmers are generally pretty sloppy with security. with html sites, script injection is common, so MVC make an attempt to limit it. so razor performs html encoding of any output strings. so:

   @myvar
   @Html.DisplayFor(m=>m.myProp)

perform html encoding when rendering their output. sometimes you need to defeat this encoding, say when the variable is an actual html string, or javascript code as in your example. then you use @Html.Raw() to prevent encoding.

note: the json.encode trick works because json is valid javascript syntax for object literals.

U guys could show how data object look like before json.encode and how things look like after json.encode. Hope you will answer with right example.

[RESOLVED]Noob question: editing/viewing cshtml pages in visual studio

Ok, so literally today I’ve decided I need to make the leap to MVC.  I’ve worked with c# .Net for several years and would like to try converting a large application I wrote to MVC.  So I opened my existing solution and added a boilerplate MVC project via
VS2013.  Started poking around at the cshtml pages and noticed I can’t view them like I do with my non-MVC project.  All I can do is edit straight code – looks like if I want to see what it looks like I have to crank up the application.  Is that correct or
am I missing something?

There is no design view available for MVC applications. View them in your browser instead.

[RESOLVED]Can't get custom @font-face to work on server (mvc4 site)

The site is http://test.conscientia.se , please have a look. I have literaly been sitting here for hours trying to get my Helvetica Neue fonts to work.

I am using following font-face declarations in application.css

@font-face { 
    font-family: HelveticaNeue; 
    src: url('/fonts/HelveticaNeue/eot/HelveticaNeue.eot'); /* IE9 Compat Modes */
    src: url('/fonts/HelveticaNeue/eot/HelveticaNeue.eot') format('embedded-opentype'), /* IE6-IE8 */
         url('/fonts/HelveticaNeue/woff/HelveticaNeue.woff') format('woff'), /* Modern Browsers */
         url('/fonts/HelveticaNeue/ttf/HelveticaNeue.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('/fonts/HelveticaNeue/svg/HelveticaNeue.svg#svgFontName') format('svg'); /* Legacy iOS */
}

@font-face { 
    font-family: HelveticaNeue; 
    font-weight: bold;
    src: url('/fonts/HelveticaNeue/eot/HelveticaNeue-Bold.eot'); /* IE9 Compat Modes */
    src: url('/fonts/HelveticaNeue/eot/HelveticaNeue-Bold.eot') format('embedded-opentype'), /* IE6-IE8 */
         url('/fonts/HelveticaNeue/woff/HelveticaNeue-Bold.woff') format('woff'), /* Modern Browsers */
         url('/fonts/HelveticaNeue/ttf/HelveticaNeue.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('/fonts/HelveticaNeue/svg/HelveticaNeue-Bold.svg#svgFontName') format('svg'); /* Legacy iOS */
}

@font-face { 
    font-family: HelveticaNeue; 
    font-weight: lighter;
    src: url('/fonts/HelveticaNeue/eot/HelveticaNeue-Light.eot'); /* IE9 Compat Modes */
    src: url('/fonts/HelveticaNeue/eot/HelveticaNeue-Light.eot') format('embedded-opentype'), /* IE6-IE8 */
         url('/fonts/HelveticaNeue/woff/HelveticaNeue-Light.woff') format('woff'), /* Modern Browsers */
         url('/fonts/HelveticaNeue/ttf/HelveticaNeue.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('/fonts/HelveticaNeue/svg/HelveticaNeue-Light.svg#svgFontName') format('svg'); /* Legacy iOS */
}

I have placed my fonts on the server in the following location, taking HelveticaNeue.woff as an example:

[...]/test.conscientia.se/public_html/Fonts/HelveticaNeue/woff/HelveticaNeue.woff

and looking at developer tools this is clearly the location it is trying to request, and it’s getting 404 on that.

This code works locally when I run it using Visual Studio, but for some reason it does not work on the server.

What could be the issue? A thousand thanks to anyone who answers!

You need to add the mime types to IIS

<system.webServer>
  <staticContent>
    <mimeMap fileExtension=".woff" mimeType="application/x-woff" />
  </staticContent>
</system.webServer>

.

Thanks so much for pointing me in the right direction! What finally worked was this:

<staticContent>
           <remove fileExtension=".woff" />
           <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
        </staticContent>

[RESOLVED]Select Multiple into SQL Question

Afternoon guys,

I am hoping this is a simple question!

I have a select multiple field in my form:

<select multiple="" name="formSelectThings">
<option value="Bob">Bob Smith</option>
<option value="Fred">Fred Jones</option>
<option value="John">John Doe</option>
</select>

I want to insert each item that is selected into a table – What is the best way of going about this? I have figured out how to combine each value and insert however I am wanting them to be separate items in a table.

Cheers!

Hi,

There is so many way to achieve this requirement.

1) Insert comma(,) separated value in table

2) create child table i.e one to many  (master child table)

Thanks,

Dharmesh.Kotadiya

Hi,

There is so many way to achieve this requirement.

1) Insert comma(,) separated value in table

2) create child table i.e one to many  (master child table)

Thanks,

I already have a table structure – I am just not sure of the best method to insert them into the database?

When the form is posted, the items will be available in Request["formSelectThings"] as a comma-separated string. If you want to insert a new row per item, you have to use string.Split to generate an array from the string and then loop through that, inserting
as you go:

foreach(var item in Request["formSelectThing"].Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries)){
    var sql = "INSERT INTO MyTable (MyField) VALUES (@0)"
    db.Execute(sql, item);
}

Mikesdotnetting

When the form is posted, the items will be available in Request["formSelectThings"] as a comma-separated string. If you want to insert a new row per item, you have to use string.Split to generate an array from the string and then loop through that, inserting
as you go:

foreach(var item in Request["formSelectThing"].Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries)){
    var sql = "INSERT INTO MyTable (MyField) VALUES (@0)"
    db.Execute(sql, item);
}

I was literally 30 seconds from posting!!

I found this which has helped but you have fast tracked it (once again) Mike!! 

http://forums.asp.net/t/1861123.aspx?Insert+multiple+selected+items+to+SQLCE+in+Webmatrix+and+Razor

[RESOLVED]Using CssClass in my local variable

Hi all

I have list of values coming form the table and i want to use the different style for different message type

Example:

if my MessageType is Alert then i want my message be displayed in red and bold

if my MessageType is Announcement then i want my message be displayed in black and bold

Table data:

PortalMessage                            MessageType
This is a Alert Message                     Alert
This is Announcement                Announcement
This is Info1                                        Info1

HTML: 

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

Code Behind

DataSet ds = DataConnections.RunSPReturnData_PortalAdmin("MY procedure", null);

foreach (DataRow dr in ds.Tables[0].Rows)

{
text = "<br />" + dr.ItemArray[1].ToString();
Literal1.Text += text;
}

Thanks in advance

You can use the below code to chagne the color of messagetext based on the message type

 foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string textval = string.Empty;
                if (dr.ItemArray[1].ToString() == "Alert")
                {
                    textval = "<br /><font style='color : red;'><b>" + dr.ItemArray[0].ToString() + "</b></font>";
                }
                else if (dr.ItemArray[1].ToString() == "Announcement")
                {
                    textval = "<br /><font style='color : black;'><b>" + dr.ItemArray[0].ToString() + "</b></font>";
                }
                else if (dr.ItemArray[1].ToString() == "Info1")
                {
                    textval = "<br />" + dr.ItemArray[0].ToString() ;
                }

                Literal1.Text += textval;
            }

Complete Sample:

DataTable table1 = new DataTable("DataTable1");
            table1.Columns.Add("PortalMessage");
            table1.Columns.Add("MessageType");
            table1.Rows.Add("This is a Alert Message", "Alert");
            table1.Rows.Add("This is Announcement", "Announcement");
            table1.Rows.Add("This is Info1 ", "Info1");
            DataSet ds = new DataSet();
            ds.Tables.Add(table1);

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string textval = string.Empty;
                if (dr.ItemArray[1].ToString() == "Alert")
                {
                    textval = "<br /><font style='color : red;'><b>" + dr.ItemArray[0].ToString() + "</b></font>";
                }
                else if (dr.ItemArray[1].ToString() == "Announcement")
                {
                    textval = "<br /><font style='color : black;'><b>" + dr.ItemArray[0].ToString() + "</b></font>";
                }
                else if (dr.ItemArray[1].ToString() == "Info1")
                {
                    textval = "<br />" + dr.ItemArray[0].ToString() ;
                }

                Literal1.Text += textval;
            }

Rendered Demo

Hi A2H

Thanks for the quick reply … it worked.

I was wondering is there any way i can do it dynamically. In is example there for only 3 different style. original i have 7 style but i have to repeat  the code for 7 different condition check

Can i do it once and point to different cssclass

Thanks once again

 

I have changes the HTML to class and small change to code fixed it

foreach (DataRow dr in ds.Tables[0].Rows)
{
string textval = string.Empty;
textval = "<div class=’" + dr.ItemArray[1].ToString() + "’>" + dr.ItemArray[0].ToString() + "</div>";
Literal1.Text += textval;

}

then I can give any style in CSS Example:

.Alert
{
       color:blue;
}
.Announcement
{
        color:red;
}
.Info1
{
        color:yellow;
}

[RESOLVED]How to select within select with FOREACH loop

I need to make selection from a table then for each result make new query (from the same table)

Here is how i`m trying to do:

var contracts = db.Query(   "SELECT DISTINCT NrKontrates " +
                                "FROM PPI",
                                fillimi, perfundimi);

var payments = "SELECT * FROM PPI WHERE NrKontrates = '@0'";

@foreach(var contract in contracts){
            <table id="datatable1" class="table table-striped table-hover display">
                <thead>
                    <tr><td colspan="4">Numri i Kontrates: @kontrata.NrKontrates</td></tr>
                    <tr>
                        <th>Provizion</th>
                        <th>RDKA</th>
                        <th>ArsyeAn</th>  
                        <th>PrimiAn</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach(var payment in db.Query(payments, kontrata.NrKontrates))
                    {
                        <tr>
                            <td>@payment.IDPol</td>
                            <td>@payment.Seria</td>
                            <td>@payment.Primi</td>
                            <td>@payment.NrKontrates</td>
                        </tr>
                    }
                </tbody>
            </table>
            }

I got no errors but i dont get what i except

pitoaxiu

var contracts = db.Query(   "SELECT DISTINCT NrKontrates " +
                                "FROM PPI",
                                fillimi, perfundimi);

You have passed in two parameter values (fillimi and perfundimi) but have no placeholders in your SQL for them, so they have no effect at all.

pitoaxiu

var payments = "SELECT * FROM PPI WHERE NrKontrates = '@0'";

You have surrounded your parameter placeholder with single quotes which turns it into a literal string. Parameter placeholders should not have quotes around them:

var payments = "SELECT * FROM PPI WHERE NrKontrates = @0";

I think all you need is this:

var sql = "SELECT * From PPI";
var data = db.Query(sql).GroupBy(d => d.NrKontrates);
@foreach(var group in data){
    <table id="datatable1" class="table table-striped table-hover display">
        <thead>
	    <tr><td colspan="4">Numri i Kontrates: @group.Key</td></tr>
	    <tr>
	        <th>Provizion</th>
                <th>RDKA</th>
                <th>ArsyeAn</th>  
                <th>PrimiAn</th>
            </tr>
        </thead>
        <tbody>
        @foreach(var payment in group)
        {
            <tr>
                <td>@payment.IDPol</td>
                <td>@payment.Seria</td>
                <td>@payment.Primi</td>
                <td>@payment.NrKontrates</td>
            </tr>
        }
        </tbody>
    </table>
}

You might need to alter the SQL depending on whether the parameters are supposed to be used as filters or something, but the approach above results in just one query and much better performance.

That is because of the WHERE clause. You wanted to pass a parameter, but you’re passing a string to it. 

You should be using this code instead of the code you’re having right now. 

var payments = "SELECT * FROM PPI WHERE NrKontrates = @0";

This would pass the kontrata.NrKontrates as a parameter. Secondly, why are you using concatenation when you can write that query command in one string. Like this, 

// And also, no parameter will be allowed in Query
// There is no WHERE column_name = @0 AND column_name2 = @1

db.Query("SELECT DISTINCT NrKontrates FROM PPI", fillimi, perfundimi);

Are you missing any thing in the first query? If not, simply skip this one and change your second query. 

Thank you a lot Mike i have also looking for this answer elsewhere and got too many suggestion but this is exactly what i wanted.

Thank you again

[RESOLVED]How to keep DIV from not closing when using Show/Hide?

I’m trying to show/hide a div but upon clicking the show button the DIV only stays open for a few seconds. How come this happening?

Here is the code on WebForm.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#show").click(function () {
            $("div").show();
        });
        $("#hide").click(function () {
            $("div").hide();
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </form>
</body>
</html>

And here is the code in WebForm.aspx.cs:

namespace WebServiceClient
{
    public partial class WebForm11 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("<button id='show'>Show</button>");
            sb.Append("<button id='hide'>Hide</button>");

            sb.Append("<div style='display:none'>"); // Content to show/hide
            sb.Append("<p>Show this content</p>");
            sb.Append("</div>");

            Literal1.Text = sb.ToString();

        }
    }
}

I would prefer the DIV to stay open until I Click the hide button. How come it automatically closes?

The page is probably refreshing, you need to cancel the button click so the form doesn’t submit

    $(document).ready(function () {
        $("#show").click(function (e) {
           e.preventDefault();
            $("div").show();
        });
        $("#hide").click(function (e) {
           e.preventDefault();
            $("div").hide();
        });
    });

Ohh, sounds reasonable. I didn’t think of that. Still wouldn’t know what to do about it Wink

Superb Cool

That did the trick!!! Thanks!

[RESOLVED]How to Show/Hide only one div at a time?

I have several sections/DIVs that I want to display and only one div at a time. How do I accomplish that?

As for now every section / every DIV is displayed.

Here is the code in WebForm.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#show").click(function (e) {
            e.preventDefault();
            $("div").show();
        });
        $("#hide").click(function (e) {
            e.preventDefault();
            $("div").hide();
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </form>
</body>
</html>

And here is the code in WebForm.aspx.cs:

namespace WebServiceClient
{
    public partial class WebForm11 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            string[] sectionArray = new string[3] { "Section 1", "Section 2", "Section 3" };

            for (var section = 0; section < sectionArray.Length; section++)
            {
            sb.Append("<button id='show'>Show</button>");
            sb.Append("<button id='hide'>Hide</button>");

            sb.Append("<div style='display:none'>"); // Content to show/hide
            sb.Append(sectionArray[section]);
            sb.Append("</div>");

            sb.Append("<hr />");

            Literal1.Text = sb.ToString();
            }

        }
    }
}

So how can I show only one DIV/Section at a time? Not all at the same time.

You are trying to use the element selector in jquery and it will select all element with given tagname(div). You need to differentiate the div based on the button clicked an then use the jquery ID selector to select each div.

Sample Implemenation:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#show").click(function (e) {
                e.preventDefault();
              //  $("div").show();
                $('#' + this.name).show();
            });
            $("#hide").click(function (e) {
                e.preventDefault();
                // $("div").hide();
                $('#' + this.name).hide();
            });
        });
    </script>
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>

C#:

 StringBuilder sb = new StringBuilder();

                string[] sectionArray = new string[3] { "Section 1", "Section 2", "Section 3" };

                for (var section = 0; section < sectionArray.Length; section++)
                {
                    sb.Append("<button name='" + section + "' id='show'>Show</button>");
                    sb.Append("<button name='" + section + "' id='hide'>Hide</button>");

                    sb.Append("<div id='" + section + "' style='display:none'>"); // Content to show/hide
                    sb.Append(sectionArray[section]);
                    sb.Append("</div>");

                    sb.Append("<hr />");

                    Literal1.Text = sb.ToString();
                }

Ptolemy

I have several sections/DIVs that I want to display and only one div at a time. How do I accomplish that?

Hi Ptolemy,

You can try to use the jquery ui according to complete your feature like the example below.

<head>

  <meta charset="utf-8">

  <title>jQuery UI Accordion - Default functionality</title>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>

  <link rel="stylesheet" href="/resources/demos/style.css">

  <script>

  $(function() {

    $( "#accordion" ).accordion();

  });

  </script>

</head>

<body>

 

<div id="accordion">

  <h3>Section 1</h3>

  <div>

    <p>

    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer

    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit

    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut

    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

    </p>

  </div>

  <h3>Section 2</h3>

  <div>

    <p>

    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet

    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor

    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In

    suscipit faucibus urna.

    </p>

  </div>

  <h3>Section 3</h3>

  <div>

    <p>

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.

    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero

    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis

    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

    </p>

    <ul>

      <li>List item one</li>

      <li>List item two</li>

      <li>List item three</li>

    </ul>

  </div>

  <h3>Section 4</h3>

  <div>

    <p>

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus

    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in

    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia

    mauris vel est.

    </p>

    <p>

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.

    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per

    inceptos himenaeos.

    </p>

  </div>

</div>
</body>

More information you can follow below

https://jqueryui.com/accordion/

Thanks.

Best Regards!

A2H

You are trying to use the element selector in jquery and it will select all element with given tagname(div). You need to differentiate the div based on the button clicked an then use the jquery ID selector to select each div.

Sample Implemenation:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#show").click(function (e) {
                e.preventDefault();
              //  $("div").show();
                $('#' + this.name).show();
            });
            $("#hide").click(function (e) {
                e.preventDefault();
                // $("div").hide();
                $('#' + this.name).hide();
            });
        });
    </script>
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>

C#:

 StringBuilder sb = new StringBuilder();

                string[] sectionArray = new string[3] { "Section 1", "Section 2", "Section 3" };

                for (var section = 0; section < sectionArray.Length; section++)
                {
                    sb.Append("<button name='" + section + "' id='show'>Show</button>");
                    sb.Append("<button name='" + section + "' id='hide'>Hide</button>");

                    sb.Append("<div id='" + section + "' style='display:none'>"); // Content to show/hide
                    sb.Append(sectionArray[section]);
                    sb.Append("</div>");

                    sb.Append("<hr />");

                    Literal1.Text = sb.ToString();
                }

Thanks for your help!

Now all divs doesn’t open at the same time so at least some progress.  But only the first div opens when clicking on the button for section 1. When I click on buttons related to section 2 and 3 nothing happens. I don’t know why because your code does seem
to make sense.

What could be the problem?

I found another solution that worked very well:

http://andylangton.co.uk/blog/development/accessible-showhide-content-jquery

But anyway I want to thank both of you for your feedback.

I’m not really sure about how this ui accordion thing would work, but might look into that deeper later on.