ASP:DynamicControl rendering HTML rather then displaying source - asp.net

I have a ASP dynamic scaffolding project in which I am customizing a details view. In my data source I have a few fields containing HTML and I would like to display the rendered HTML on the page rather then the source HTML as it is currently doing. The control looks like this.
<tr>
<td class="DDLightHeader">
<asp:Label ID="lblStatementHtml" runat="server" Text="Statement" />
</td>
<td>
<asp:DynamicControl ID="dcStatementHtml" runat="server" DataField="StatementHtml" />
</td>
</tr>
I am confused on how to proceed since the default view for this control is the Text.ascx which is apparently nothing more then a literal (the same base control I use to render the HTML on my site. I am comfortable with creating a new FieldTemplate to render the HTML, but how can I force the html to render rather then display its source view.

To resolve the above issue I had to create anew FieldTemplate
HTML.ascx
<%# Control Language="C#" CodeBehind="HTML.ascx.cs" Inherits="ProductDynamicCMS.HTML" %>
<asp:Literal runat="server" ID="Literal1" />
HTML.cs
using System;
using System.Web.DynamicData;
using System.Web.UI;
namespace ProductDynamicCMS
{
public partial class HTML : FieldTemplateUserControl
{
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
object val = FieldValue;
if (val != null)
Literal1.Text = val.ToString();
}
public override Control DataControl
{
get
{
return Literal1;
}
}
}
}
Then applied the UIHint for this class to the field display in the details view template.
<tr>
<td class="DDLightHeader">
<asp:Label ID="lblStatementHtml" runat="server" Text="Statement" />
</td>
<td>
<asp:DynamicControl ID="dcStatementHtml" runat="server" DataField="StatementHtml" UIHint="HTML" />
</td>
</tr>
And all was well.

Related

will it change .aspx.cs file to take data from html element after converting asp controls into html?

my question was that when I send the request to the web server, of course, the web server will take the request and give me a page that will be in the HTML format so I want to know when the web server will execute asp server-side controls into HTML format than in the Testing. aspx.cs file will be changed as well? it means these two lines int no1 = Convert.ToInt32(textbox1.Text);
int no2 = Convert.ToInt32(textbox2.Text);
these two lines will be converted into like this int no1=Convert.ToInt32(Response["textbox1"]);
int no1=Convert.ToInt32(Response["textbox2"]); these two lines will be converted like this or not
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Testing.aspx.cs" Inherits="login.Testing" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="background-image:url(C:\Users\Sudarshan\source\repos\login\login\Images\uWjEogFLUTBc8mSvagdiuP.jpg)">
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
Enter the Number 1:<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Enter the Number 2:<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<center>
<br />
<br />
<asp:Button ID="button1" runat ="server" Text="Add" Height="38px" OnClick="Unnamed1_Click" Width="101px" /> </center>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
--------------------------------------------------------------
Testing.aspx.cs
using System;
using System.Collections.Generic;
using System. Linq;
using System. Web;
using System.Web.UI;
using System.Web. UI.WebControls;
namespace login
{
public partial class Testing: System.Web. UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
int no1 = Convert.ToInt32(textbox1.Text);
int no2 = Convert.ToInt32(textbox2.Text);
int result;
result = no1 + no2;
Response.Write(result);
}
}
}

ASP.Net - how to display a "You are not authorized" message when authorization fails

My ASP.Net app handles authorization with roles just fine, but when someone reaches an unauthorized page, he is kicked back to the login page without any sort of warning.
Is there a way of passing a message to the default login page? Alternatively, is there a way to have an authorization failure redirect to a page that's not the default login page (while maintaining the default page when authorization is needed for the first time)?
I think some of you are misunderstanding what I have.
Here is my login.aspx:
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Security" %>
<script runat="server">
void Logon_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(Username.Text, Password.Text))
{
FormsAuthentication.RedirectFromLoginPage(Username.Text, false);
}
else
{
Msg.Text = "Your user name or password is incorrect";
}
}
</script>
<html>
<head id="Head1" runat="server">
<title>Login Screen</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:center;">
<h3>You must be logged in to use this application</h3>
<table>
<tr>
<td>
User Name:</td>
<td>
<asp:TextBox ID="Username" runat="server" /></td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="Username"
Display="Dynamic"
ErrorMessage="User Name needs to be filled in"
runat="server" />
</td>
</tr>
<tr>
<td>
Password:</td>
<td>
<asp:TextBox ID="Password" TextMode="Password"
runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
ControlToValidate="Password"
ErrorMessage="Password needs to be filled in"
runat="server" />
</td>
</tr>
</table>
<asp:Button ID="Submit1" OnClick="Logon_Click" Text="Log On"
runat="server" />
<p>
<asp:Label ID="Msg" ForeColor="red" runat="server" />
</p>
</div>
</form>
</body>
</html>
and here is the "admin" controller page:
namespace MyApp.Controllers
{
public class AdminController : Controller
{
[Authorize(Roles="SuperUser")]
public ActionResult Index()
{
return View();
}
}
}
If the person who logged in is in the system but does not have the SuperUser role, it returns to the login screen - what I want to do is, I want the user to differentiate between the login screen showing up because the user hasn't logged in yet and the screen showing up because the user did not have the correct role.
Actually, what I want to do for an unauthorized user is to display a separate screen that displays a message and then lets the user return to the app's home screen.
Create a class derived from AuthorizeAttribute and override the method: HandleUnauthorizedRequest
using System.Web.Mvc;
using System.Web.UI.WebControls;
namespace MvcAttributes.Infrastructure.customAttributes
{
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
// redirect to your Error page
context.Result =new RedirectResult("/UnauthorizedRequest.html");
// if you want to redirect to some action, use:
// new RedirectResult("/UnAuthorizedUsers/ErrorDetails");
}
}
}
and apply MyAuthorizeAttribute as shown below:
[MyAuthorizeAttribute]
public class ProductController :Controller
{
You can use the ContentResult to return a plain string:
In MVC, how do I return a string result?
if bAuthorized
{
return Content("Unauthorized.");
}
assuming your function looks like this:
function isAuthorized() {
$.ajax({
url: '/Home/isAuthorized',
type: "POST",
data: "some data",
success: function (ret) {
$("#displayresult").html(ret);
},
error: function (ret) {
$("#cdisplayresult").text("Something went wrong!");
}
});
}

Displaying multiple dynamic posts using asp.net

I am new to asp.net (web forms) and want to get some information from database and then display this information in the form of posts , like heading , paragraph and an image. If there are three rows in database there would be three posts. I have done this using asp.net code in .aspx file
<%
while (reader.Read())
{ %>
<article class="col1">
<h2><%= reader.GetValue(0).ToString()%></h2>
<p class="pad_bot1"><%= reader.GetValue(1).ToString()%></p>
<img src="<%= reader.GetValue(2).ToString() %>" class="img" alt="">
</article>
<% } reader.Close(); %>
But I read somewhere that the code must be separated and it should be written in .aspx.cs file. What's the way to do this ? Assigning id's to the h and p tags and then assigning them values like this :
while (reader.Read())
{
h.InnerText = reader.GetValue(0).ToString();
p.InnerText = reader.GetValue(1).ToString();
}
But this does not solve the problem , because the posts will not be displayed in a loop i.e. 3 times.
I want to know a most suitable solution , thanks in advance
This is my code you can modify as you wish
Code behind
// Here's your object that you'll create a list of
private class Products
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
}
// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{
// The the LIST as the DataSource
this.rptItemsInCart.DataSource = ListOfSelectedProducts;
// Then bind the repeater
// The public properties become the columns of your repeater
this.rptItemsInCart.DataBind();
}
Aspx code
<asp:Repeater ID="rptItemsInCart" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("ProductDescription")%></td>
<td><%# Eval("ProductPrice")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
Using web forms, that would be easiest to solve using a Repeater control.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx

.NET/html, element does not exist error when selecting dropdown.ClientID

On button click I want to get the value of a dropdown but for somereason when I go into the code it fails with error 'Exdd' does not exist in the current context. The ExTypeDD is in my listview as a dropdown and I'm just trying to get the value from it. The server side is generating this code and not my browser.
$('.Updt')
.click(function() {
var parent = $(this).parent().prev();
var TypeNode = parent.children("#<%=Exdd.ClientID %>").first();
<asp:ListView runat="server" id="ListView1" >
<LayoutTemplate>
<table id="tablesorter" style="border:solid 1px black;width:55%;">
<thead>
<tr>
<th>
Address
</th>
</tr>
</thead>
<tbody>
<tr id="itemPlaceholder" runat="server" />
</tbody>
<tfoot>
</tfoot>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<select id="Exdd"
class="Nbr1" style="width: 90px" >
<option value=""><%# Eval("Type")%></option>
<option value="0">Home</option></select>
</td>
<td>
<input type="button" id="btn_update" class="Updt" value="Update" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
You are in a ListView. You have as ExTypeDD as you have rows.
So you can not reference ExTypeDD successfully outside of the item template (there are more than one)
You may try ( after wrapping that up in a $(document).ready )
$('.Updt')
.click(function() {
var tr = $(this).closest('tr');
var TypeNode = tr.find("select.Nbr1").first();
//...
});
This is because you are trying to access an HTML element on the server side as a server side control. You could make your select element into a server side control by simply adding runat="server" to it like such:
<select id="ExTypeDD" runat="server" class="Nbr1" style="width:90px">
But after that you would still have the issue that this control, although accessible on the server side now, it does not have the id of ExTypeDD because it is dynamically created in the ItemTemplate of your ListView which generates a unique ID value for each newly created control . You can verify this by viewing source on the page rendered in the browser and checking the ID value on the select element.
To do what you're trying to do on the server side you would need to do something along the lines of this:
Add an onItemCreated event handler to your ListView:
<asp:ListView runat="server" id="ListView1" onItemCreated="ListView1ItemCreated">
Replace this:
<input type="button" id="btn_update" class="Updt" value="Update" />
With this:
<asp:button id="btn_update" text="Update" runat="server" />
Add the event handler to the code behind:
protected void ListView1ItemCreated(object sender, ListViewItemEventArgs e){
var myselect = (HtmlSelect)e.Item.FindControl("ExTypeDD");
var mybutton = (Button)e.Item.FindControl("btn_update");
mybutton.OnSubmit += (o,e) => {
// do something with myselect selected value
var selectedvalue = myselect.Value;
};
}
NOTE: the above code is not tested and probably won't compile, you will need to make necessary corrections, but it should give you the idea for a way to solve your problem. Hope it helps.

Set TD at runtime (depending on Label.text)

I have some tabular data, when the label has some specific value I need to make it show off.
Trying to do by styling the TD.
My C# sets the value for Label1.text
Can you think of any other way for doing so? It's throwing ambiguity error.
<% if (Label1.Text == "1") { %>
<td style="background:#ffedad; border:#e3a345; color:#cd5c0a"><asp:Label ID="Label1" runat="server" /></td>
<% } else {%>
<td><asp:Label ID="Label1" runat="server" /></td>
<% } %>
EDIT
Did something else (and cleaner).
Worked on some code behind variables along with some new td.alt on my css file to get the value of the label. If it's 1, then I set a
classLabel variable to alt and then I just set the class inside the td
<td class="<%classLabel%>"><asp:Label ID="Label1" runat="server" /></td>
Still, I'm getting and error on this last line in my aspx page, any ideas where the error is?
You can try this with a single line :
<td <%=Label1.Text != "1"?"":"style='background:#ffedad; border:#e3a345; color:#cd5c0a'"%>><asp:Label ID="Label1" runat="server" /></td>
Setting the style code behind and with a css class would be cleaner IMHO
Hope this will help
You can call the code behind method which will return the formatted HTML string that can be directly rendered by the browser. In that code behind method you can do almost anything: access any type of database or any business logic.
Possible return div element encapsulating the content (without style).
You can return divs with different ids or classes by having if-else logic inside the code-behind method. Then you can write different CSS styles to apply to different divs.
<% if (Label1.Text == "1") { %>
<td style="background:#ffedad; border:#e3a345; color:#cd5c0a">
<%# generateOutput() %></td>
<% } else {%>
<td> <%# generateOutput() %> </td>
<% } %>
Instead of having if-else in asp.net markup, you can simply have
<%# generateOutput() %>
and return the whole content from code behind and write styles in CSS files.
If the content to be displayed is less or less complicated this second approach will work, otherwise you may prefer first approach.
However if you are accessing the data directly from database you can you ASP.NET data controls like GridView, style them in templates and also filter the data using querystring or form values.

Resources