Is there any way to replace Response.Write? - response.write

My problem is, I have the following function:
function change_tarif(param) {
var arrTarif = <% Response.Write(Session["Tarif"]); %>
.....
}
Session["Tarif"] - contains multidimensional array List and when I'm loading my page it's giving this Error that
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
When I delete <% Response.Write(Session["Tarif"]); %> it doesn't give this error. So, how can I replace this code to get array List from Session["Tarif"] without using the code blocks <% %>?
This is my Array List code in C#:
public void getTarifList()
{
int intRows = 0;
string strTarif = "null";
Session["Tarif"] = "null";
SqlCommand cmdTarif = new SqlCommand("sp_SIMPay_GetTarifList");
cmdTarif.CommandType = CommandType.StoredProcedure;
DataTable dtTarif = SQL.GetData(cmdTarif);
if (dtTarif.Rows.Count > 0)
{
intRows = dtTarif.Rows.Count;
strTarif = "new Array(" + intRows + ");";
int intIndex = 0;
foreach (DataRow dRows in dtTarif.Rows)
{
strTarif += "arrTarif[" + intIndex + "] = new Array('" + dRows["TarifName"] + "', '" + dRows["ProviderID"] + "', '" + dRows["CodeID"] + "');";
intIndex++;
}
}
else
{
strTarif = "null";
}
Session["Tarif"] = strTarif;
}
My full script:
function change_tarif(param) {
var arrTarif = <% Response.Write(Session["Tarif"]); %>
var select = document.getElementById('TarifList');
var i = 0;
if (arrTarif != null) {
for (i = 0; i < arrTarif.length; i++) {
if (arrTarif[i][1] == '98' && param == '98') {
clear_tarif();
select.options[select.options.length] = new Option('' + arrTarif[i][0] + '', '' + arrTarif[i][2] + '');
break;
}
else {
clear_tarif();
select.options[select.options.length] = new Option('Default Tarif', '');
}
}
}
}

This happens because somewhere in your page code you do something like (just an example - it doesn't matter that it's a Label here, any dynamically added/removed control would trigger the error):
Label lbl = new Label ();
lbl.Xxxx = ...;
Controls.Add ( lbl ); // this is what triggers your issue
When you have <%= ... %> in the same container where you also try to dynamically add controls through the use of the Controls collection of that container (Page, Panel, etc.), you'll get that error that you saw.
If you can, try to remove the code that dynamically adds/removes the control to the container (the same container where you have the <%= ... %> and then your <%= ... %> block will start working.
To remove the dynamic logic that adds/removes control(s), simply put those controls into the container like any other control, like
<asp:Label runat="server" id="lbl" ... />
and then simply show/hide the control when you need it. This way the control is always present in the page, you won't have to add/remove it during run-time and then you can have code blocks in the same container.
Here's a quick example that would create this error:
...
<div runat="server" id="div1">
<asp:Label runat="server" id="lbl1" /><br />
<span>Name: <%= Session["name"] %></span>
</div>
...
// in code-behind
protected override void OnLoad ( EventArgs e )
{
Label lbl2 = new Label ();
lbl2.Text = "Time: " + DateTime.Now.ToString ();
// Error: you cannot modify the Controls collection if
// the same control contains code blocks
div1.Controls.Add ( lbl2 );
}

You can use Expression (Equivalent to Response.Write()).
function change_tarif(param) {
var arrTarif = <%= Session["Tarif"] %>;
}
EDIT : I've customized your code,
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
getTarifList();
}
public void getTarifList()
{
Session["Tarif"] = "null";
StringBuilder sb = new StringBuilder();
sb.AppendLine("new Array(" + 3 + ");");
for(int i=0;i<3;i++)
{
sb.AppendLine("arrTarif[" + i + "] = new Array('A" + i + "', 'B" + i + "', 'C" + i + "');");
}
Session["Tarif"] = sb.ToString();
}
And markup,
<script type="text/javascript">
function change_tarif(param){
var arrTarif = <% Response.Write(Session["Tarif"]); %>
return arrTarif;
}
console.log(change_tarif('test'));
</script>

Related

Validate a dynamically generated CheckBox

I'm generating an asp:CheckBox dynamically and I need to validate that it is checked with a CustomValidator().
private void AddCheckBox(HtmlGenericControl newDiv, AdditionalFields field)
{
var additionalFieldDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
additionalFieldDiv.Attributes.Add("class", "additional-field-row");
var additionalLabel = new RadLabel();
additionalLabel.Text = field.Label;
additionalLabel.ID = "AdditionalLabel" + field.ControlId;
additionalLabel.CssClass += "title ";
additionalLabel.Width = new Unit(field.LabelWidth ?? 175);
if (field.Required??false) additionalLabel.CssClass += "additional-field-required";
var additionalField = new System.Web.UI.WebControls.CheckBox();
additionalField.ID = "AdditionalField" + field.ControlId;
additionalField.CssClass += "additional-field-checkbox";
additionalField.Width = new Unit(field.Width ?? 200);
var customValidator = new CustomValidator();
customValidator.ID = "CustomValidator" + field.ControlId;
//customValidator.ClientValidationFunction = "CheckBoxValidation(AdditionalField"+ field.ControlId +")";
customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
customValidator.ErrorMessage = string.IsNullOrEmpty(field.ErrorMessage) ? field.Label + " required" : field.ErrorMessage;
customValidator.CssClass += "additional-fields-validator";
customValidator.Display = ValidatorDisplay.Dynamic;
customValidator.ValidationGroup = "valGroup";
customValidator.EnableClientScript = true;
newDiv.Controls.Add(additionalFieldDiv);
additionalFieldDiv.Controls.Add(additionalLabel);
additionalFieldDiv.Controls.Add(additionalField);
if (field.Required ?? false)
{
additionalFieldDiv.Controls.Add(customValidator);
}
}
I get an error if I try to use customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
Control 'AdditionalField9' referenced by the ControlToValidate property of 'CustomValidator9' cannot be validated.
I have several other controls on the page that are in the validation group "valGroup" and I like the CheckBox validated client side. If I can't use the ControlToValidate property do I need to use JavaScript, and if so how do I pass the ID of the CheckBox to validate?
<script type = "text/javascript">
function ValidateCheckBox(sender, args) {
if (document.getElementById("<%=AdditionalField9.ClientID %>").checked == true) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
</script>
Hope you can help

How can I get the proper value of proper button with this method?

Code:
for (int i = 1; i < butonsayisi; i++)
{
int buttonvalue = 1;
var buttonmenu = new Button
{
HeightRequest = 100,
WidthRequest = 100,
Margin = 5,
CornerRadius = 15,
BackgroundColor = Color.FromRgb(192,192,192),
};
buttonmenu.Clicked += butonmenu;
butonlar.Children.Add(buttonmenu);
if (baglanti.State.ToString() == "Open")
{
}
else
{
baglanti.Open();
}
SqlCommand getir = new SqlCommand("select * from butonlar where id = '" + i.ToString() + "'", baglanti);
SqlDataReader oku = getir.ExecuteReader();
while (oku.Read())
{
buttonmenu.Text = oku.GetValue(1).ToString();
baglanti.Close();
break;
}
async void butonmenu(object o, EventArgs args)
{
baglanti.Open();
SqlCommand getirici = new SqlCommand("select * from butonlar where id = '" + buttonvalue.ToString() + "'", baglanti);
SqlDataReader okuyucu = getirici.ExecuteReader();
while (okuyucu.Read())
{
butonadi = okuyucu.GetValue(2).ToString();
baglanti.Close();
break;
}
await DisplayAlert("Alert","Deneme " + butonadi,"OK");
buttonvalue++;
}
}
I have to reach the right buttonvalue.
butonsayisi counts how much row I have in database, this is how I create buttons and after that I edit the name of buttons with buttonmenu.Text = oku.GetValue(1).ToString(); in index 1 I have the the name of buttons.
So in index 2 I have another table name. When I press the button, I have to get the right table name. With this method I use, I am taking another button's index 2.
await DisplayAlert("Alert","Deneme " + butonadi,"OK"); is just for testing.
i did it guys!
simply i did;
SqlCommand getirici = new SqlCommand("select * from butonlar where butonadi = '" + buttonmenu.Text + "'", baglanti);
SqlDataReader okuyucu = getirici.ExecuteReader();
while (okuyucu.Read())
{
butonadi = okuyucu.GetValue(2).ToString();
baglanti.Close();
break;
}
i used to get the value from id now i get from name of button so it works!

How to append a string to view in mvc3?

HI all i have some values...using them i am building a string in my controller i wan to display the string in my view page....
here is my controller code
[ChildActionOnly]
public ActionResult History()
{
//if(Session["DetailsID"]!=null)
//{
int id = Convert.ToInt16(Session["BugID"]);
var History = GetBugHistory(id);
return PartialView(History);
//}
//int id1 = Convert.ToInt16(Session["BugID"]);
//var History1 = GetBugHistory(id1);
//return PartialView(History1);
}
/// <summary>
///To the List of Resolutions and Employeenames Based on BugID
/// </summary>
/// <param>Bug Id</param>
/// <returns>BugHistory</returns>
public List<BugModel> GetBugHistory(int id)
{
var modelList = new List<BugModel>();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("History", conn);
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add(new SqlParameter("#BugID", id));
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
StringBuilder sb = new StringBuilder();
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new BugModel();
model.FixedBy = ds.Tables[0].Rows[i]["FixedByEmployee"].ToString();
model.Resolution = ds.Tables[0].Rows[i]["Resolution"].ToString();
model.AssignedTo = ds.Tables[0].Rows[i]["AssignedEmployee"].ToString();
model.Status = ds.Tables[0].Rows[i]["Status"].ToString();
model.ToStatus= ds.Tables[0].Rows[i]["ToStatus"].ToString();
modelList.Add(model);
sb.Append("'" + model.FixedBy + "'" + "has updated the status from" + "'" + model.ToStatus + "'" + "to" + "'" + model.Status + "'" + "and Assigned to" + "'" + model.AssignedTo + "'");
}
return modelList;
}
}
How should i show this string in my partial view page using a foreach loop
anil,
I'd suggest creating a partialview (_BugModelList.cshtml) that handles purely the output display of the BugModel. This may look something like this:
#model IList<BugModel>
<table>
<thead>
<tr>
<th>Fixed by</th>
<th>From Status</th>
<th>To Status</th>
<th>Assigned to</th>
</tr>
</thead>
#{
foreach (var item in Model)
{
<tr>
<td>#item.FixedBy</td>
<td>#item.ToStatus</td>
<td>#item.Status</td>
<td>#item.AssignedTo</td>
</tr>
}
}
</table>
or, if you wanted the single string as per your controller (untested obviously):
#model IList<BugModel>
#{
foreach (var item in Model)
{
<p>
#{ "'" + item.FixedBy + "'"
+ " has updated the status from "
+ "'" + item.ToStatus + "'"
+ " to " + "'" + item.Status + "'"
+ " and Assigned to " + "'" + item.AssignedTo + "'"; }
</p>
}
}
this would then be called from your main view as per the action that you presently have. Obviously, I've formatted it as table but you can refactor that to suit, the logic remains the same.
[Edit] - re-reading your question, you probably want to present the list as a table, rather than as an unordered list. See edit above

Is there anyway to apply telerik combo on dynamic created select-box via JavaScript?

I have java script which create select box depend of ajax result.
For example, if result = 2x combo, i create 2x select box via javascript.
if (this.Type == "combo") {
var result = "<label>" + this.Name + "</label><select onChange='ProChange(this)' name='" + this.ID + "'>";
result += "<option value='0'>Please select</option>";
for (var i = 0; i < this.Values.length; i++) {
var resultId = this.Values[i].ID;
var resultName = this.Values[i].Name;
result += "<option value= " + resultId + ">" + resultName + "</option>";
}
result += "<option value='-1'>Other</option>";
result += "<input type='text' name='"+this.ID+"other' style='display:none;' id='"+this.ID+"' />";
result += "</select>";
So my main question is, can i apply telerik style on dynamic created select box?
You can use the Telerik RadFormDecorator
<telerik:RadFormDecorator ID="rfd_combo" runat="server" DecoratedControls="Select" />
and after creating your controls by javascript:
$find("<%= rfd_combo.ClientID %>").decorate();
More details: http://www.telerik.com/support/kb/aspnet-ajax/formdecorator/decorate-dynamically-added-controls-by-using-radformdecorator.aspx

AJAX getting truncated on paragraph

I'm having a strange problem when trying to updated a div with a couple of paragrahs of text from AJAX.
Here are functions I'm using:
var receivePapers = getXmlHttpRequestObject();
function get_papers(myCat){
if (receivePapers.readyState == 4 || receivePapers.readyState == 0) {
receivePapers.open("GET", 'http://server/path/tocode/file.php?get_papers=1&student_id=1&category=' + myCat, true);
receivePapers.onreadystatechange = handlereceivePapers;
receivePapers.send(null);
}
}
function handlereceivePapers() {
if (receivePapers.readyState == 4) {
var container_div = document.getElementById('paper_container');
var xmldoc = receivePapers.responseXML;
var paper_nodes = xmldoc.getElementsByTagName("paper");
var n_papers = paper_nodes.length;
// Clear the whole container div.
container_div.innerHTML = "";
container_div.innerHTML = "<table class='categoryHeader' width='100%'><tr><th class ='categoryHeader' width='80%' ><br/> " + paper_nodes[1].getElementsByTagName("category")[0].firstChild.nodeValue + "</br> <br/><br/></th></tr>";
container_div.innerHTML += "<tr><td>";
for (i = 0; i < n_papers; i++) {
var paper_id = paper_nodes[i].getElementsByTagName("paper_id");
var paper_title = paper_nodes[i].getElementsByTagName("paper_title");
var paper_desc = paper_nodes[i].getElementsByTagName("paper_desc");
var paper_time = paper_nodes[i].getElementsByTagName("paper_time");
var user_real_name = paper_nodes[i].getElementsByTagName("user_real_name");
var summary_div = document.createElement('div');
summary_div.innerHTML += "<table class='paper'><tr><td class='paperLike' width=80px rowspan=2 valign='top'><div id='" + paper_id[0].firstChild.nodeValue + "'> <img src='images/Like.png' style='padding-top:5px' border='0' /></div></td><td><table width='100%'><tr><td class='paperTitle' style='background-color:white; text-align=left; '><a class='paperTitle' style='padding-left:0;' href='#" + paper_id[0].firstChild.nodeValue + "'>" + paper_title[0].firstChild.nodeValue + "</a></td><td class='paperName' style='margin-right:0; width:200px; background-color:white; text-align:right; vertical-align:text-top;'><span align='right' style='background-color:white; text-align:right; vertical-align:text-top; ' > " + user_real_name[0].firstChild.nodeValue + "</span></td></tr></table></td><td rowspan='2' class='paperLength' style='width:80px; text-align:right; padding-top:8px;' >" + paper_time[0].firstChild.nodeValue + " minutes</td></tr><tr><td class='paperDescription' align='left' colspan='1'>" + paper_desc[0].firstChild.nodeValue + "</td></tr></table>";
container_div.appendChild(summary_div);
}
container_div.innerHTML += "</tr></td></table";
}
}
Here is the XML that's getting returned:
<root>
<paper id="23">
<paper_id>23</paper_id>
<paper_title>title</paper_title>
<paper_desc>
First paragraph of desc
<br/>
<br/>
Second paragraph of desc
<br/>
<br/>
Third paragraph of desc
<br/>
</paper_desc>
<paper_time>45</paper_time>
<user_real_name>Bob Student</user_real_name>
<user_id>2322</user_id>
<category>Languages</category>
</paper>
...
When I push the content to container_div only the first paragraph is showing up. If I stick a Javascript alert() in to return paper_desc it only contains the first paragraph. I've tried looking for other nodes but this says there's only 1 node:
alert(paper_nodes[i].getElementsByTagName("paper_desc").length);
You use paper_desc[0].firstChild.nodeValue
paper_desc[0] is a set of nodes: text nodes and br nodes. You get only the first child of this set, so you get only the first text.
Your alert() call only shows you have only one paper_desc node, not how many nodes you have inside.
I also found strange that you used paper_nodes[1] but I don't know if there is a second node in your XML and if you really want to target it.

Resources