I have this user control:
<user:RatingStars runat="server" product="<%= getProductId() %>" category="<%= getCategoryId() %>"></user:RatingStars>
You can see that I fill in the product and category by calling two methods:
public string getProductId()
{
return productId.ToString();
}
public string getCategoryId()
{
return categoryId.ToString();
}
I do not understand why, in the user control, when I take the data received (product and category) it gives me "<%= getProductId() %>" instead of giving the id received from that method...
Any help would be kindly appreciated...
Edit: Solved with: product='<%# getProductId() %>'
Last problem: in the user control I have this:
public string productId;
public string product
{
get
{
return productId;
}
set
{
productId = value;
}
}
So, I expect that the productId is set up ok in the user control.
Unfortunately it is null when I try to use it...
Is there anything I wrote that's incorrect?
So that you get compile-time checking, you can give your user control an ID and then set its Product and Category properties in C# like this:
ASPX:
<user:RatingStars id="myUserControlID" runat="server" Product="<%= getProductId() %>" Category="<%= getCategoryId() %>"></user:RatingStars>
CS:
myUserControlID.Product = GetProductId();
myUserControlID.Category = GetCategoryId();
Also, as 5arx mentions, once you've populated that then refreshing your page will reload your control and you'll lose the Product and Category IDs. You can handle that by using ViewState on the properties in your user control, like this:
private const string ProductKey = "ProductViewStateKey";
public string Product
{
get
{
if (ViewState[ProductKey] == null)
{
// do whatever you want here in case it's null
// throw an error, return string.empty or whatever
}
return ViewState[ProductKey].ToString();
}
set
{
ViewState[ProductKey] = value;
}
}
NOTE: I've updated the property name casing to follow convention, as it just makes more sense to me that way! Personally, I'd always suffix IDs with ID (eg: ProductID) to distinguish it from a property that contains a Product object. Read more about coding standards here: Are there any suggestions for developing a C# coding standards / best practices document?
Please post some more of your code?
A couple of things:
productId is an object reference (to a string object) which means:
unless you write some intialisation code to 'fill' it with a string reference at the start, it will be null.
if you create a string e.g. string x = new String() x will be an empty string, which you can think of as "" without the quotes. (It is a string, but its empty because it has no characters in it).
you can just write return productId; - no need to call ToString() on a string.
Your page does not have an out-of-the-box mechanism to store variables across postbacks. You need to use ViewState or hidden form fields to do this.
Related
I have a viewmodel to update data (from API, not view) with params like below:
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
i just want to update "name", so my param like below:
{
"name": "my name"
}
its name changed become "my name" but its email and phone become null. how to avoid params changed to be null if they don't exist in input form?
Thanks...
You'll have to adjust whatever does the update so that it understands "null means do not set a value, rather than set the value to null"
For example if you're running a db update query you could:
UPDATE person
SET
name = COALESCE(#name, name),
email = COALESCE(#email, email),
phone = COALESCE(#phone, phone)
WHERE
id = #id
Now if any value is supplied as null the update will set the column to the same value it is currently (ie no-op)
If you're adjusting a c# object you can take a similar approach:
var p = db.FindPerson(viewmodel.PersonId);
p.Name = viewmodel.Name ?? p.Name;
...
As I see, you have a problem or misunderstanding in your software design.
If this API endpoint is meant to just update the name field, then you should not have the other fields in your ViewModel. However, if you update the other fields in some cases, then you should pass their values as well.
So maybe you need to call a Get endpoint first to get the all data you need in your client "web page for example" and then allow this client to resend the full JSON, not just the name.
Or you may just need an endpoint that just takes the name.
Another solution, in case you're using EF, is to ignore the null fields when updating the EF entity.
e.g.
...
var entity = dbContext.Employees.FirstOrDefault(e => e.Id == 3);
entity.Name = request.Name;
await dbContext.SaveChangesAsync();
...
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;
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
So, I am trying to programmatically add in a ModelFilter to my ObjectListView that will look at two (or more) columns and filters on each separately. Currently, I think that ObjectListView only supports one filter, but I may be missing something in the code/documentation.
As an example, one of my intended filters is to look at column "Active" and that has values of "A" or "T". Another column is a Supervisor Name. So, I want to find all entries where Supervisor name = "Smith" and Active = "A".
I can get the filter to work for either of these options separately using TextMatchFilter, but cannot figure out how to get both to work at the same time.
The minor problem I see is that if the Supervisor Name contains an "A", then using the standard Filter will return the whole row. I have been able to get around that by programmatically setting the Searchable property for columns to false if I don't want to look at them, and then turn them back on once the list is filtered. However, I have a feeling that if I turn Searchable on for the Supervisor column, I will get the unwanted results.
Does anyone know of a way to get the filter to work on multiple columns, using only the indicated columns for each filter?
(I have no sample code to show that helps in solving this. However, if you really want to see what I have for my filtering code, I will be happy to add that; it is in VB however).
Current Code - This looks at a value chosen by the user (searchMeth) and enables searching on that column. It then does the search for what was entered in the txtSearch box. However, in addition to this, I want to add in an additional filter for Supervisor. (See the AndAlso comment
olvEmps.UseFiltering = True
OlvColumn1.Searchable = False
OlvColumn2.Searchable = False
OlvColumn4.Searchable = False
OlvColumn3.Searchable = False
OlvColumn5.Searchable = False
Select Case searchMeth
Case "Name"
OlvColumn1.Searchable = True
Case "Employee Number"
OlvColumn2.Searchable = True
Case "Department"
OlvColumn3.Searchable = True
End Select
olvEmps.OwnerDraw = True
Dim tFilter As BrightIdeasSoftware.TextMatchFilter = BrightIdeasSoftware.TextMatchFilter.Contains(olvEmps, txtSearch.Text)
'andalso olvColumn5 = supeName?
olvEmps.ModelFilter = tFilter
olvEmps.DefaultRenderer = New BrightIdeasSoftware.HighlightTextRenderer(tFilter)
OlvColumn1.Searchable = True
OlvColumn2.Searchable = True
OlvColumn3.Searchable = True
OlvColumn4.Searchable = True
OlvColumn5.Searchable = True
I'm sure the PredicateBuilder solution will work, but ObjectListView comes with a simpler solution already.
TextMatchFilter can be limited to which columns it searches via the Columns property. Set this to an array of columns that you want to consider.
TextMatchFilter filter1 = TextMatchFilter.Contains(olvEmps, txtSearch.Text)
filter1.Columns = new [] { this.olvColumn1, this.olvColumn2 };
You can combine two filters using the CompositeAllFilter to match two or more other filters.
this.olvEmps.ModelFilter = new CompositeAllFilter(new List<IModelFilter> { filter1, filter2 });
Though I don't yet fully understand your deal, I'll give it a shot with the PredicateBuilder that is part of the LINQKit assembly which you can download here.
As such, filtering on multiple columns shall get easy. Perhaps shall you consider to reset the binding of your ObjectListView control once your source collection has been filtered.
Grossly, I would do about the following:
Load your datum;
Display them through data binding;
Once a column is clicked for filter, make a call to your "Filter" method which will apply your predicates;
Rebind your control with the new filtered collection.
Please refer to the PredicateBuilder documentation at the link provided previously. Another example to building dynamic filters is illustrated here: "How would this query translate into a dynamic Linq expression?" for a search engine I implemented.
In my case, the filters were applied directly against the database results. Aside, it can even be used in your situation with in-memory datum since it is Linq based.
I'm sure I'll be able to provide further assitance when you post your code sample for filtering the information.
EDIT #1
After I have read the code sample provided, here's what I believe would do the trick. As for the Searchable property, I am no familiar of this approach, so maybe I can miss something important out of your code and if it is so, feel free to point me what I could have missed. =)
Note that I assume that all of your datum are string, since I am verifying whether your datum is null or white space. Furthermore, the way I see it, to filter a result set is to bring visible only records which meet certain criterion. You don't want to see what doesn't meet the criterion. It's the same as a WHERE clause in SQL.
public class FilterCriterion {
public bool HasEmployeeName { get { return !string.IsNullOrWhiteSpace(EmployeeName); } }
public bool HasEmployeeNumber { get { return !string.IsNullOrWhiteSpace(EmployeeNumber); } }
public bool HasDepartment { get { return !string.IsNullOrWhiteSpace(Department); } }
public string EmployeeName { get; set; }
public string EmployeeNumber { get; set; }
public string Department { get; set; }
}
The FilterCriterion class shall be used to apply any filter that you want against your data source, collection or whatsoever.
var employees = LoadEmployeesFromUnderlyingDataStore();
var criterion = new FilterCriterion();
switch(searchMeth) {
case "Name": filter.EmployeeName = "the name to filter by"; break;
case "EmployeeNumber": filter.EmployeeNumber = "the number to filter by"; break;
case "Department": filter.Department = "the department to filter by"; break;
}
var filter = PredicateBuilder.True<Employee>(); // assuming you have an employee class.
if (criterion.HasEmployeeName)
filter.And(e => e.Name.ContainsLike(criterion.EmployeeName));
if (criterion.HasEmployeeNumber)
filter.And(e => e.EmployeeNumber.ContainsLike(criterion.EmployeeNumber));
if (criterion.HasDepartment)
filter.And(e => e.Department.ContainsLike(criterion.Department));
var filteredEmployees = employees.Where(filter);
// Supply your ObjectListView the way you're used to and this shall function.
Aside, you could also, if you have to deal with such string variables write a ContainsLike extension method to the string class.
namespace System {
public static class StringExtensions {
public static bool ContainsLike(this string input, string value) {
if (string.IsNullOrWhiteSpace(input) || string.IsNullOrWhiteSpace(value)) return false;
input = input.ToLower().RemoveDiacritics();
value = value.ToLower().RemoveDiacritics();
if (string.IsNullOrWhiteSpace(input) || string.IsNullOrWhiteSpace(value)) return false;
return input.Contains(value);
}
public static string RemoveDiacritics(this string input) {
return input == null ? null :
Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(input));
}
}
}
I do hope this helps, otherwise inform me of what I misunderstood from your question and we'll try to figure this out together.
Should you need the VB version of this code, I'll try to translate to the best of my VB knowledge.
This code is provided as is and has not been tested, except for both the string extension methods.
Dictionary<string, EmployeeInfo> employeeInfoList = new Dictionary<string, EmployeeInfo>();
employeeInfoList = EmployeeInfoProxy.GetAllEmployeeInfo(TenantId);
if (employeeInfoList != null)
{
List<EmployeeInfo> employee = new List<EmployeeInfo>(employeeInfoList.Values);
ViewData["Name"] = employee[0].Name;
ViewData["Salary"] = employee[0].Salary;
ViewData["Department"] = employee[0].Department;
ViewData["Designation"] = employee[0].Designation;
ViewData["Address"] = employee[0].Address;
ViewData["Address1"] = employee[0].Address1;
}
the above code is working fine.if the employee has only one record,so i had hardcoded employee[0].
if there are more rows,how to pass those index to employee(for eg employee[\i should get the value dynamically here].
If I understand your question correctly, given a List you could use linq to grab a single employee.
EmployeeInfo singleEmployee = employee.Where( x => x.Id).SingleOrDefault();
if (singleEmployee != null)
{
do something here
}
that said, I don't know if you have a 'key' against the employee like Id or similar.
To get by index, you have a bigger round trip (outputting the emploees to a grid or something similar, allowing a click that passes in the index of the employee you want, and access the single eployee that way).
Unless you're heavily employing caching in the 'EmployeeInfoProxy.GetAllEmployeeInfo()' method though, I'd say you want a 'GetEmployeeInfoById()' and again, I'll harp back to the need for your EmployeeInfo to have a unique Id of some description - you will make your life so much easier.
Hope this helps.
Cheers,
Terry
[in addition]
if employeeListInfo has 3 entries, then to access each of them I'd say the best way would be to create a viewmodel (it looks like this is MVC), but worst case scenario you could do:
List<EmployeeInfo> employee = new List<EmployeeInfo>(employeeInfoList.Values);
ViewData["Employees"] = employee;
then in your view, just do:
<% foreach(EmployeeInfo employeeDetails in ViewData["Employees"] as List<EmployeeInfo>) { %>
<!-- you will be looping through each employee here, so you can do as you wish
<% } %>
I wouldn't say this is best practice - using a ViewModel would likely represent a better way to do this, though the above will certainly give you a solution that will work in your case.