Dynamically load asp.net Content from database - c#

My solution consists out of a single page, "Content.aspx" which I use to populate with different types of html data depending on the querystring.
I need to know, if possible, how to load aspx content in my page.
I've tried adding code like :
<asp:Label ID="lblName" runat="server"></asp:Label>
But it gets displayed as plain text.
Here is my code that I use to retrieve the data from the database.
string category = Request.QueryString["category"].ToString();
using (MyEntity dbc = new MyEntity())
{
ContentTables cms = (from c in dbc.ContentTable
where c.Name == category && c.Status == true
select c).First();
divHeader.InnerHtml = cms.Header;
divContent.InnerHtml = cms.Content;
if (cms.Header == "dataPage")
{
/*Code Requirement Here*/
}
}
Any help will be greatly appreciated. Thanks

Use StringBuilder and Literal
StringBuilder sb = new StringBuilder();
sb.append("Your Contain From Database");
Literal1.Text = sb.ToString(); //Bind Contain to Litral
The StringBuilder AppendFormat method is useful for generating text based on a pattern.

Related

Lucene boosting not working

I'm indexing a document and setting the boost as follows:
document.SetBoost(5f);
because I want certain documents to appear before. For example, I want more recent news to show first.
When I do the search, like this:
var parser = new QueryParserEx(Version.LUCENE_29, "contents", analyzer);
parser.SetDefaultOperator(QueryParser.Operator.AND);
parser.SetMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
Query query;
query = parser.Parse("text*");
The query gets parsed as a WildcardQuery and internally it's using this:
{Lucene.Net.Search.MultiTermQuery.AnonymousClassConstantScoreAutoRewrite}
Not sure why it's still using a Constant Score rewriter. Can someone explain?
I also believe I cannot use at search-time boosting as I don't need to boost certain terms, but certain documents (eg, most recent news appear first).
PS: This is not a duplicate of this question.
Nevermind. I was using a custom implementation of the QueryParser that had the method NewTermQuery overwritten.
Something like this:
protected override Query NewTermQuery(Term term)
{
var field = term.Field();
var text = term.Text() ?? "";
if (field == "contents" &&
text.Length >= 3 &&
text.IndexOfAny(new[] { '*', '?' }) < 0)
{
var wq = new WildcardQuery(new Term(field, text + "*"));
return wq;
}
return base.NewTermQuery(term);
}
And the WildcardQuery was not taking that configuration. All I had to do is call wq.SetMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); inside that if.

JavaScript added rows not accessible in c#

I am making a web page in asp.net. I have created an HTML table with runat="server". I added some rows to it using JavaScript by getting values from input boxes. I need these rows accessible in code behind c#. When I use this table in code behind, it gives me just one row, which I added as a table heading in the HTML section. It does not consider the rows added in JavaScript. Is there any way to access these rows?
My HTML Code:
<table id="tblStaff" border="1" runat="server">
<tr>
<th>S. No.</th>
<th>Staff Name</th>
<th>Room</th>
<th>Phone No.</th>
<th>Remove</th>
</tr>
</table>
Javascript Code:
function addStaff()
{
var tbl = document.getElementById('tblStaff');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cell0 = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cell0.appendChild(textNode);
var cell1 = row.insertCell(1);
var textNode = document.createTextNode(document.getElementById('txtStaffName').value);
cell1.appendChild(textNode);
var cell2 = row.insertCell(2);
textNode = document.createTextNode(document.getElementById('txtRoomNo').value);
cell2.appendChild(textNode);
var cell3 = row.insertCell(3);
textNode = document.createTextNode(document.getElementById('txtPhoneNo').value);
cell3.appendChild(textNode);
var lastCell = row.insertCell(4);
var el = document.createElement('input');
el.type = 'button';
el.name = 'btnDelete' + iteration;
el.id = 'btnDelete' + iteration;
el.value = 'Remove';
el.size = 40;
el.setAttribute('onclick', 'deleteRow(' + iteration + ');');
lastCell.appendChild(el);
}
I'd recommend to let the user add some data via a form, then send it to the server and store it where you want. If this was successful, add the rerendered table to the response and render it on the client or add just the new row client side. On server side you cannot access the new rows, but you can access its data models, what should be sufficient.
If you want further advice you should elaborate on why you want to access those rows server side.
EDIT:
Have a look at this fiddle. There you see the structure your table has to be. Now if you want to add an user, just add a new row in this format with index of users in name incremented. Now if you hit submit, all users will be send as an array to the server where you can iterate through them and send an email.
You web api method could look like:
//route url/to/api
public void AddNewUser(User[] users)
{
//iterate through users and send email
}
Try this
using System.Web.UI.HtmlControls;
foreach (HtmlTableRow row in tblStaff.Rows)
{
string txtCell0 = row.Cells[0].InnerText;
string txtCell1 = row.Cells[1].InnerText;
}
It looks like your addStaff() function only adds to the table in the frontend. If I may point out, the C# is executed server side, and so, the rows added by your javascript do not exist at the time when your C# is looking for them.
Like Florian Gl suggested, you could include an ajax submit in your addStaff() function, that also sends whatever row the javascript displays in the table in the browser, to the C# in the backend. Once you have the data in your C#, you can proceed with sending the email or can even opt to save a database...

Ajax jquery autocomplete in ASP.NET MVC 5 C#

I know there's a lot of these kind of post but I wasn't able to find any that suited me. I don't have knowledge of ajax and jquery (in fact I've just started with MVC and ASP.NET) so I need your help in this little thing.
There must be almost everywhere this kind of silly thing, I want to write a city name in a combobox, dropdownlist (or whatever) and using a method that I've already created which returns a list of locations (city, country and state names) that match the entered city. I want it to be dinamyc that's why I thought AJAX would solve this (but any other solution is accepted)
I found this jQuery autocomplete but I don't understand where to implement it. I want the combobox to match the bootstrap theme. Could someone tell me if this is an appropiate solution and if so where do I put the ajax content and else? (by where I mean, is it in the view, or controller or where?)
Or you could give mi a hint here is the method I've created for getting the elements from the database:
public List<LocationsViewModel> GetHeadquarter(string query)
{
var context = new HeadquarterContext();
//var city = context.Cities.Where(p => p.Name == query).Single();
//var province = context.Provinces.Where(p => p.ProvinceID == city.Province).ToList();
//foreach(Province prov in province) {
//}
var hq =
from c in context.Cities
join p in context.Provinces on c.Province equals p.ProvinceID
join co in context.Countries on p.Country equals co.CountryID
where c.Name == query
select new { country = co.Name, province = p.Name, city = c.Name };
List<LocationsViewModel> listLocation = new List<LocationsViewModel>();
foreach (var hqe in hq)
{
LocationsViewModel loc = new LocationsViewModel();
loc.City = hqe.city;
loc.Country = hqe.country;
loc.Province = hqe.province;
listLocation.Add(loc);
}
return listLocation;
}
Lets see if we can get it to work.
View:
This is added in your view, #Url.Action(Action, Controller) is the Action that is the source for the autocomplete function.
<input type="search" class="form-control ui-autocomplete"
data-autocomplete="#Url.Action("Autocomplete", "Home")" />
Controller (Home):
As you can see the Action Autocomplete was used to search for a product. I have an instance of my database entity called '_db' and have select a table called 'product_data' (can also use a Stored Procedure). I'm using LINQ to query the datasource and store it in the variable 'model', so it's querying where the 'term' StartsWith what is typed in the textbox, it takes the top 10 and for each one it add label and product. [{"label":value}]
public ActionResult Autocomplete(string term)
{
try
{
var model = _db.product_data // your data here
.Where(p => p.product.StartsWith(term))
.Take(10)
.Select(p => new
{
// jQuery UI needs the label property to function
label = p.product.Trim()
});
// Json returns [{"label":value}]
return Json(model, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Settings.ReportException(ex);
return Json("{'ex':'Exception'}");
}
}
JavaScript:
This code is when you select a value from the list that is displayed from your search. The 'window.location.href' redirects to a different controller once a value from the autocomplete has been selected.
// submits form upon selecting a value
var submitAutocompleteForm = function (event, ui) {
var $input = $(this); // the HTML element (Textbox)
// selected value
$input.val(ui.item.label); // ui.item.label = the label value (product)
window.location.href = "/Product/Details?id=" + ui.item.label;
};
The next function sets up the autocomplete API. You declare your options, the above is optional and it comes under select, the source is required and it points to the data-attribute on the HTML element.
var createAutocomplete = function () {
var $input = $(this); // the HTML element (Textbox)
var options = {
// selecting the source by finding elements with the 'data-' attribute
source: $input.attr("data-autocomplete"), // Required
select: submitAutocompleteForm // Optional
};
// apply options
$input.autocomplete(options);
};
// targets input elements with the 'data-' attributes and each time the input changes
// it calls the 'createAutocomplete' function
$("input[data-autocomplete]").each(createAutocomplete);
You'll have to reference the jQueryUI file for autocomplete to work.

How I Populate a list<> in two different Gridview

Based on the answers and comments that I have been provide, I made the following modifications. Since I have other things than the two Gridviews I am not making any modifications to the load method. I am trying to split the collection when I bind it.
The Gridviews are:
<asp:GridView id ="gvClosed" runat = "server"/>
<asp:GridView id ="gvDraft" runat = "server"/>
The Bind:It does bind but the same data in both GV's
private void bindFiles(bool reload)
{
int size = 10;
List<File> closedFiles = new List<File>();
List<File> draftFiles = new List<File>();
if (ViewState["Files"] != null)
closedFiles = (List<File>)ViewState["Files"];
//draftFiles= (List<File>)ViewState["Drafts"];
else
closedFiles = loadFiles(((User)Session["currentUser"]).ID);
draftFiles = loadFiles(((User)Session["currentUser"]).ID);
List<File> listFiles = new List<File>();
foreach (File f in closedFiles)
listFiles.Add(f);
bool loadPrimary = Session["filterPrimary"] != null ? Convert.ToBoolean : false;
bool loadAll = Session["ViewAllUserFiles"] != null ? Convert.ToBoolean : false;
foreach (File d in draftFiles)
listFiles.Add(d);
if (loadPrimary)
listFiles = listFiles.FindAll(delegate(File f)
{
return f.Modified == true;
});
//Binding to the database
gvFiles.DataSource = listFiles;
gvFiles.DataBind();
gvDraftFiles.DataSource = listFiles;
gvDraftFiles.DataBind();
showHideSortArrows(gvFiles, GridViewType.File);
//showHideSortArrows(gvDraftFiles, GridViewType.Drafts);
Split your collection into two collections and then bind them separately individually to their appropriate GridViews. Better yet, pass a parameter to your loading method that you can use for your query to specify what sort of list you're trying to load. That way you can just load your lists using one method and not have to split anything.
If both lists contain the same data and you want to bind the same data to two or more controls, you can do that. you don't need to split it into different lists.
Even if you wish to bind only a subset of data to different controls, you can achieve that using Linq, since Linq resultsets are always IEnumerable of T.
For instance:
List<string> someList = GetStuffFromDatabase();
// binding to first control, all data
datagridControl1.DataSource = someList;
// binding to second control with subset of data
dropdownListControl1.DataSource = someList.AsEnumerable().Where( t => t.StartsWith("US-") );
and so on... The same applies to all kinds of collections... Dictionaries, et al.
ASPX:
<asp:GridView id="gvDraft" runat="server" />
<asp:GridView id="gvClosed" runat="server" />
C#:
closedList = new List<list>();
draftList = new List<list>();
if (ds.Tables.Count != 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
List ls = new List();
if (dr["list_id"] != DBNull.Value)
{
ls.ID = Convert.ToInt32(dr["list_id"]);
//I have more this is just for example
if(dr["WhateverIndicatesClosed"] == true)
{
closedList.Add(ls);
}else{
draftList.Add(ls);
}
}
}
}
gvDraft.DataSource = draftList;
gvDraft.DataBind();
gvClosed.DataSource = closedList;
gvClosed.DataBind();
You could also use linq to separate the lists, but as you are iterating through the dataset anyway, you may as well split the lists there.

HtmlEncode string within IQueryable without altering bound data

I'm binding an ASP.NET control to the result of a LINQ query. I'd like to HtmlEncode one of the properties of the contained objects before binding to the control, but I want to do it without altering the data because I do a DataContext.SubmitChanges() later on. How can this be done?
Code that won't work:
var ds = (from s in dc.SearchResults
orderby s.datetime descending
select s)
.Take(int.Parse(ConfigurationManager.AppSettings["RecentItemQty"]));
foreach (SearchResult sr in ds)
sr.Query = Server.HtmlEncode(sr.Query);
rSearches.DataSource = ds;
rSearches.DataBind();
Your could encode it when you do your binding...
<asp:YourDataBoundControl>
<ItemTemplate>
Query: <span><%# Server.HtmlEncode((string)Eval("Query")) %></span>
</ItemTemplate>
</asp:YourDataBoundControl>
Dummy me. I just need to HtmlEncode it within the OnItemDataBound() event.
Have two copies of the data:
from s in dc.SearchResults
orderby s.datetime descending
select new {
Original = s,
Encoded = Server.HtmlEncode(s.Query)
};
Or you could use HttpUtility.HtmlEncode('string');
Both are valid but the one above is available anywhere within an application easier than loading up HttpContext.Current.Server.HtmlEncode.

Categories