How do you Request[""] with a Dynamic Variable? Request["#Variable"]? - c#

I'm building a form, where the number of questions, or inputs on the form varies depending on the value in a database.Each input on the form is a radio type. The name of the tags are dynamic and are loaded from the database using #db.row.questionID which would look something like: <span name=#id> and equal a value of 1 through whatever queries were requested.
My issue is, i wrote the form using post, and i want to submit the values back into a separate database, but i dont know how to request multiple values, that changes dynamically based on query.
Sample code i wrote, it doesnt give me any errors, but it doesnt give me any results either.
foreach(var prow in poll){
var Question = prow.PollId;
if (Request.Form["#prow.PollId"] == "A") {
int AnsA = row.ResultsA;
AnsA = AnsA + 1;
db.Execute("UPDATE Results SET ResultsA=#0 WHERE ResultsId=#1", AnsA, Question);
}
i have also tried:
if (Request["prow.PollId"] == "B") {
int AnsB = row.ResultsB;
AnsB += 1;
db.Execute("UPDATE Results SET ResultsB=#0 WHERE ResultsId=#1", AnsB, prow.PollId);
}

Do you want to get value in form with dynamic inputs? If yes, you can try this:
NameValueCollection nvc = Request.Form;
foreach (var item in Request.Form.AllKeys)
{
//do something you want.
// Examble : if(item == "A")// item will return name of input
// Note: nvc[item] return value of input
}
Update:
Request.Form.AllKeys will return all of input name in form.
We use foreach to lopp through colections of input name.
Use nvc[item] or Request.Form[item] to get value of input.
You can read this article :c#: get values posted from a form

Related

c# Object properties is loading from cache

in my win-form application, there is a method that combines some items that have been created previously, when the code is the first time to run, everything is fine, but in second and later runs combined items have the wrong length.
the code reads items from a SQL server using LINQ that has object type named "BetaData"
BetaData has a property named "Length" that is double.
I have another list that processed items is stored in name "PartList" of type "ModifiedPartList".
in method length property changes for some items, but nothing gets stored or saved on SQL.
this is the main method:
private List<ModifiedPartList> CombinePartList(ProgressBar Bar)
{
PartList.Clear();
List<BetaData> PartsinOrder = new List<BetaData>();
foreach (int view in Globals.Views)
{
List<int> OrdersInView = new List<int>();
foreach (Tuple<int, int> tuple in Globals.Orders)
{
if (tuple.Item1 == view)
{
if (!OrdersInView.Contains(tuple.Item2))
OrdersInView.Add(tuple.Item2);
}
}
if(OrdersInView.Count>0)
{
OrdersInView.Sort();
foreach (int order in OrdersInView)
{
//this is the section that problem occurs:
var parts = from BetaData in BetaContext.BetaDatas
where BetaData.ProjectName == Globals.ProjectName &&
BetaData.ProjectCode == Globals.ProjectCode &&
BetaData.ParentItem != Globals.ProjectName + "(" + Globals.ProjectCode + ")" &&
BetaData.View == view &&
BetaData.Order == order
select BetaData;
PartsinOrder.Clear();
PartsinOrder = parts.ToList();
foreach(BetaData part in PartsinOrder)
{
Bar.PerformStep();
}
}
}
PartsinOrder.Clear();
}
return PartList;
}
in the section that i have commented as problem location when the code is running for the second time, optimized length property is loaded to items instead of their original value from SQL. i cannot understand that because each time i read all items from SQL server.
the point is in this stage after that i ran the method for several times and getting the wrong results when i close the program and start it again, on first run results are true.
after selecting from SQL and converting it to list, i review items and their properties in list, and they are all true, but in foreach loop when each part comes into loop their Length property is wrong.
the issue was solved using this article and refreshing context after retrieving data from SQL

address an object by retrieving the ID name of the object from a variable

Good evening,
I am trying to get the following done. I have seen a similar post but it was related with Unity.
Anyway, I am on web forms in asp.net and I have a radiobuttonList with ID="id001"
so on my code behind, I would normally be able to get the selected value by just doing:
string value = id001.SelectedValue
However, in this situation, I don't know the exact ID name, so I have a function that retrieves it. So now I have the variable with the name of the ID. So I want to be able to now, convert the value of that variable in something like this:
string foundid = "id001"
string foundidvalue = id001.SelectedValue
I hope this makes sense.
Thanks in advance for the help.
I am assuming this one is related to your previous question. So, when you found the control, instead of using function to get the fullname, you can do like this:
foreach (Control c in Page.Form.Controls.OfType<RadioButtonList>())
{
if (c.ID.Contains("id"))
{
// string FullID = c.ID.ToString();
var radioButtonList = c as RadioButtonList;
var selectedValue = radioButtonList.SelectedValue;
}
}
You want to use FindControl.
string foundid = "id001";
var foundCtrl = (RadiobuttonList)FindControl(foundid);
var result = foundCtrl.SelectedValue;

Get rendering parameters when multiple sublayouts of the same type are on the page

I need to get the rendering parameters programmatically from my sublayout. Currently I do this as such:
var sublayout = ((Sublayout)this.Parent);
//Get all rendering
var renderings = Sitecore.Context.Item.Visualization.GetRenderings(Sitecore.Context.Device, true);
//Get the first rendering that matches the current sublayout's path
var sublayoutRendering = renderings.FirstOrDefault(r => r.RenderingItem.InnerItem["Path"] == sublayout.Path);
if (sublayoutRendering != null)
Response.Write(sublayoutRendering.RenderingItem.Parameters);
This solution came from this question and works perfectly until I have two sublayouts of the same type on the page. When this occurs obviously renderings.FirstOrDefault(r => r.RenderingItem.InnerItem["Path"] == sublayout.Path); always returns the first rendering parameter that matches the sublayouts path for both sublayouts.
How can I differentiate between them? I can see nothing that I can use to tie them together!
Edit:
To be clear, I add my sublayout in Presentation > Details, then when I click my control I set the fields in the 'Control Properties' window. I have a field called Module Source which always comes back the same - it always populates as the one highest up in the order. The values are definitely different for each sublayout but I cannot get them from the renderings.
Not sure if I'm missing something. But you can get the sublayouts rendering parameters, directly on the Sublayout. I use the following on my base Sublayout I use for all my Sitecore sublayouts - and it has no problems with rendering parameters on the same sublayout inserted multiple times :)
protected Sitecore.Web.UI.WebControls.Sublayout CurrentSublayout
{
get
{
Control c = Parent;
while (c != null && !(c is Sitecore.Web.UI.WebControls.Sublayout))
{
c = c.Parent;
if (c == null)
break;
}
return c as Sitecore.Web.UI.WebControls.Sublayout;
}
}
protected NameValueCollection CurrentParameters
{
get
{
if (CurrentSublayout == null)
return null;
NameValueCollection parms = WebUtil.ParseUrlParameters(CurrentSublayout.Parameters);
var sanitizedValues = new NameValueCollection();
for (int i = 0; i < parms.Count; i++)
{
if (!string.IsNullOrEmpty(parms[i]))
sanitizedValues.Add(parms.Keys[i], parms[i]);
}
return sanitizedValues;
}
}
You may want to check the cache settings on your sub-layout, if you don't have Cacheable VarbyParam it is not going to work for you

Newbie performance issue with foreach ...need advice

This section simply reads from an excel spreadsheet. This part works fine with no performance issues.
IEnumerable<ImportViewModel> so=data.Select(row=>new ImportViewModel{
PersonId=(row.Field<string>("person_id")),
ValidationResult = ""
}).ToList();
Before I pass to a View I want to set ValidationResult so I have this piece of code. If I comment this out the model is passed to the view quickly. When I use the foreach it will take over a minute. If I hardcode a value for item.PersonId then it runs quickly. I know I'm doing something wrong, just not sure where to start and what the best practice is that I should be following.
foreach (var item in so)
{
if (db.Entity.Any(w => w.ID == item.PersonId))
{
item.ValidationResult = "Successful";
}
else
{
item.ValidationResult = "Error: ";
}
}
return View(so.ToList());
You are now performing a database call per item in your list. This is really hard on your database and thus your performance. Try to itterate trough your excel result, gather all users and select them in one query. Make a list from this query result (else the query call is performed every time you access the list). Then perform a match between the result list and your excel.
You need to do something like this :
var ids = so.Select(i=>i.PersonId).Distinct().ToList();
// Hitting Database just for this time to get all Users Ids
var usersIds = db.Entity.Where(u=>ids.Contains(u.ID)).Select(u=>u.ID).ToList();
foreach (var item in so)
{
if (usersIds.Contains(item.PersonId))
{
item.ValidationResult = "Successful";
}
else
{
item.ValidationResult = "Error: ";
}
}
return View(so.ToList());

Only Alternating values in SPFieldMultiChoice saved

I am busy building a custom webpart with various textboxes and lookup fields. All of them are saving correctly apart from the lookup fields that allows for multiple selections. I dont have this problem with lookup fields that only allow for one value to be selected.
Below is the code for getting all the selected items in my checkboxlist, converting it to a multichoice value and assigning to my list[columnname]
try
{
SPFieldMultiChoiceValue _segmentchoices = new SPFieldMultiChoiceValue();
foreach (ListItem ls3 in _segment.Items)
{
if (ls3.Selected) _segmentchoices.Add(ls3.Value);
}
myItems["Segment"] = _segmentchoices;
myItems.Update();
}
catch (Exception ex) { _errorMessage += "||| Segment : " + ex.Message; }
The values list (_segmentchoices) is correctly created and looks like this : {;#1;#2;#3;#4;#5;#}
However when its saved it only saves values 1, 3, and 5.
My code is not generating an error, so I am at a loss at what could be wrong. Any ideas on what I need to look at? Am I going about it the wrong way?
Any assistance would be appreciated.
Thank you
I just realized you are talking about a multi-select lookup field. The format should be something like: 2;#Procedures;#3;#Systems;#7;#Services
The behavior you describe makes sense because it is probably interpreting ;#1;#2;#3;#4;#5;# like this: get the item in the lookup list with a lookupID of 1 (lookupValue is 2), lookupID of 3 (lookupValue is 4), and lookupID of 5 (lookupValue is empty)
Here is some code that you can use to update a multi-select choice field:
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[listName];
SPListItem item = list.Items[0];
SPFieldLookupValueCollection spflvc = new SPFieldLookupValueCollection();
spflvc.Add(new SPFieldLookupValue(3, string.Empty));
spflvc.Add(new SPFieldLookupValue(7, string.Empty));
item["Keywords"] = spflvc;
item.Update();
}
}
The second parameter to SPFieldLookupValue doesn't seem to care if it is passed string.Empty which also might explain why it ignores them above.

Categories

Resources