I have a dropdown box with a list of times for the user to choose from. My problem is that after the user picks their choice and then hits the submit button, the page is refreshed and then the dropdown box is set to default again - how can i have the users choice stay in the dropdown box even after a page reload? I am not sure what part of my code is needed best my Get and Post are long - but if there is a general example that would help.
CODE FROM CONTROLLER:
Here is one of my lists i load into the dropdown box:
IQueryable<User> users = _userRepository.FindAllForOffice(_currentUser.OfficeId);
userViewModel.Users = users.ToSelectList("UserId", "FullName",
userViewModel.UserId.ToString());
foreach (SelectListItem view in userViewModel.Users)
{
if (!viewData.ContainsKey(view.Text))
viewData.Add(view.Text, view.Value + "|user");
}
This is adding to the actual dropdown:
userViewModel.ViewData = viewData.ToSelectList("Value", "Key",
userViewModel.Value);
return View("UserSummary", userViewModel);
ON MY ASPX.CS page i have the following:
Page_Load
string viewType = null;
if(!String.IsNullOrEmpty(Request.QueryString["viewType"]))
{
viewType = Request.QueryString["viewType"];
}
if(!IsPostBack)
{ if (viewType == "user")
{
viewParams.Add("ViewName", "User Report");
var reportDataSource =
_userService.GetUsersReportData(beginDate, endDate, id);
reportViewer.Initialize("UserIndividual.rdlc",
new List<ReportDataSource> {reportDataSource}, viewParams);
}
I didn't add all the initialization for all the elements - didn't think it is really needed for this situation
Thanks
Check this odetocode.com article out.
To keep the selected value after a manual refresh, you could use a cookie, for example jquery.cookie. You would have to save the selected value on change and retrieve the value on page load.
I actually found a solution which was really simple and i guess i was overlooking it. I found that the same way i was passing in the values of the dates i could pass the value of the selected view type and it will remain in dropdown box until changed rather than changing after every page load.
I made the additions in my CONTROLLER file in my Get method after the button click.
this is my Post:
[HttpPost]
public ActionResult ResultSummary(ResultSummaryViewModel resultSummaryViewModel)
{
if (!ModelState.IsValid)
return View("ResultSummary", resultSummaryViewModel);
return RedirectToAction("ResultSummary",
new
{
beginDate = resultSummaryViewModel.BeginDate,
endDate = resultSummaryViewModel.EndDate,
value = resultSummaryViewModel.Value
});
}
And this is my Get:
[HttpGet]
public ActionResult ResultSummary(DateTime? beginDate = null, DateTime? endDate = null, string value="")
{
var resultSummaryViewModel = new ResultSummaryViewModel();
resultSummaryViewModel.BeginDate = beginDate;
resultSummaryViewModel.EndDate = endDate;
resultSummaryViewModel.Value = value;
.........
The code continues but this is the main part.
Related
I have a Xamarin form where I am trying to add a SyncFusion AutoComplete control. The data is a simple class with only three string fields (CUSTNMBR, CUSTNAME, ZIP). I want it to match on any of the fields and display the coresponding CUSTNMBR. Here it my line in Xaml:
<xForms:SfAutoComplete x:Name="customerAutoComplete" WidthRequest="120" BackgroundColor="White" />
In the form's code-behind constructor I call LoadCustomerData():
private async void LoadCustomerData()
{
customerAutoComplete.DataSource = await GetCustomerCodes();
customerAutoComplete.DisplayMemberPath = "CUSTNMBR";
customerAutoComplete.SelectedValuePath = "CUSTNMBR";
customerAutoComplete.SuggestionMode = SuggestionMode.Custom;
customerAutoComplete.Filter = FilterCustomers;
customerAutoComplete.AutoCompleteMode = AutoCompleteMode.Suggest;
customerAutoComplete.Watermark = "Zip Code, Customer ID, or Customer Name";
customerAutoComplete.MinimumPrefixCharacters = 3;
}
Here is my filter method.
private bool FilterCustomers(string search, object customer)
{
var text = customerAutoComplete.Text;
if (customer != null)
{
var myCustomer = (OrganizationSearchDto)customer;
if (myCustomer.CustName.Contains(text) || myCustomer.CustNmbr.Contains(text) ||
myCustomer.Zip.Contains(text))
{
return true;
}
}
return false;
}
The above code worked partially when I had customerAutoComplete.SuggestionMode = SuggestionMode.Contains but it did not match on the other two fields. Now it still runs, however nothing is shown in the dropdown list (its blank). Why is my dropdown blank? Any hints, suggestion or a hard shove in the right direction will be appreciated.
For anyone encountering this, tests to try:
Put a breakpoint on return true - is that breakpoint hit for the customer(s) you expect to be shown as suggestions?
Swap return true and return false, so it is true for all the OTHER customers - the opposite of what you want. See if it is still blank. If it is, then it isn't the filter - code elsewhere is interfering with display. Would need to show more code, or make a github containing a minimum repo that shows the problem.
[from OP] The issue was that property names on DisplayMemberPath are case sensitive, as are the filter checks.
The fix for the filter was to ignore case everywhere. E.g.
if (myCustomer.CustName.ToLower().Contains(text.ToLower()) || ...)
We have analyzed the reported query. We have achieved the requirement by using the following code snippet,
public bool ContainingSpaceFilter(string search, object item)
{
if (item != null)
{
var myCustomer = item as Employee;
if (**myCustomer.Name.ToUpper().Contains(search.ToUpper()**) || myCustomer.ID.Contains(search) ||
myCustomer.ZipCode.Contains(search))
{
return true;
}
}
return false;
}
Datagrid View in a form gets populated from a List
I have this Form with a datagridview that gets populated from a List.
When i click on the Users button on each row, a list of users also in a datagrid should appear
The datagrid on the new form gets updated by the list i pass, When i click on the Users button this is what happens:
GetUserDescriptorDetails gtUserDetails = new GetUserDescriptorDetails(name, xmlData, CreateListDynamically(name));
gtUserDetails.ShowDialog();
the CreateListDynamically method is like this:
public BindingList<xml.UserDescriptor> CreateListDynamically(string _name)
{
foreach (xml.UserDescriptor dbList in xmlData.Users)
{
if (dbList.DatabaseDescriptorName == _name)
{
users.Add(new xml.UserDescriptor() { DatabaseDescriptorName = dbList.DatabaseDescriptorName, Username = dbList.Username, Password = dbList.Password, IsAdmin = dbList.IsAdmin });
}
}
return users;
}
Now the list is fine, but every time i click on the Users button the rows duplicate, because of the users.Add. How can i solve this?
The fact that i add values is only to populate the list, is there any other way to get the list with the condition:
dbList.DatabaseDescriptorName == _name
Inside your CreateListDynamically(string _name) method, you are never clearing the previous users list, this will be why you are getting the duplication.
Add a users.Clear() before your foreach loop and the duplication should go away.
This all ofc assumes that users is a class variable since I do not see it being passed into the method as a variable
What you could also do is entirely decouple the users variable and just have a temporary variable for your resultset inside your method:
public BindingList<UserDescriptor> CreateListDynamically(string _name)
{
return new BindingList<UserDescriptor>(xmlData.Users.FindAll(x => x.DatabaseDescriptorName == _name));
}
I have looked extensively to find an answer to this question but I only get extremely close. I have a web form that I use to add and edit records. When a record is selected in the gridview, a session variable is set and then used on page load to populate the text fields. If the session variable is not set, the form will be blank and the logic run as a new record. My problem is that I can add a new record successfully - I debugged and checked to make sure the asp controls passed the proper values to the code behind - but I cannot edit a record successfully. For some reason, the code behind file does not retrieve the proper values from the text boxes. Instead, it keeps the original populated values thus defeating the purpose of the edit. I imagine it is a binding issue but I am unsure and have searched upon end. Here is my code behind file:
protected void Page_Load(object sender, EventArgs e)
{
resultOutput.Visible = false;//Output results as to whether or not a record was added successfully is automatically hidden at page load
//Checking to see if session variable has been created
if (Session["editID"] != null)
{
//Create objects to get recipe data
dbCRUD db = new dbCRUD();
Recipe editRecipe = new Recipe();
//Grabbing session ID
var id = Convert.ToInt32(Session["editID"]);
//Call method to retrieve db data
editRecipe = db.SelectRecord(id);
//Populate results to text boxes
recordID.Text = editRecipe.Recipe_ID.ToString();
addName.Text = editRecipe.Name;
addTypeDDL.SelectedValue = editRecipe.Meal;
addDifficultyDDL.SelectedValue = editRecipe.Difficulty;
addCookTime.Text = editRecipe.Cook_Time.ToString();
addDirections.Text = editRecipe.Directions;
//Change Button Text
submitRecord.Text = "Edit Record";
//Change Title Text
addEditTitle.Text = "Edit Recipe";
}
}
protected void submitRecord_Click(object sender, EventArgs e)
{
Recipe recipe = new Recipe();
dbCRUD newRecord = new dbCRUD();
//Variables for execution results
var modified = "";
int returned = 0;
//Creating the recipe Object to pull the values from the form and
//send the recipe object as a parameter to the method containing insert stored procedure
//depending on Add or Edit
//recipe.Recipe_ID = int.Parse(recordID.Text);
recipe.Name = addName.Text.ToString();
recipe.Meal = addTypeDDL.SelectedValue.ToString();
recipe.Difficulty = addDifficultyDDL.SelectedValue.ToString();
recipe.Cook_Time = int.Parse(addCookTime.Text);
recipe.Directions = addDirections.Text.ToString();
//Checking to see if the page is loaded for edit or new addition
if (Session["editID"] != null)
{
recipe.Recipe_ID = Convert.ToInt32(Session["editID"]);
//If recordID exists, recipe will be passed to UpdateRecord method
returned = newRecord.UpdateRecord(recipe);
modified = "has been edited.";
Session.Remove("editID");
}
else
{
//If recordID does not exist, record will be passed to InsertRecord method (new recipe)
returned = newRecord.InsertRecord(recipe);
modified = "added";
}
//Method returns 0 if successful, 1 if sql error, 2 if other error
if (returned == 1)
{
resultOutput.Text = "There was an sql exception";
resultOutput.Visible = true;
}
else if (returned == 2)
{
resultOutput.Text = "There was a non sql exception";
resultOutput.Visible = true;
}
else
{
resultOutput.Text = "\"" + addName.Text + "\" recipe " + modified;
resultOutput.Visible = true;
}
}
Any object passed to my edit method is successful, however, as I mentioned, it does not grab the newly updated text box values.
Did you try checking PostBack property , Your code is loading the data everytime the page is posted back. So when you update the values in the form and hit update button. The Page_Load method is called first and it reloads all the data (replaces your updated values on the form) and then hit the update button event handler. So everytime your old values are being saved.
You may remove the code from page_load method and put it where you are setting the Session["EditId"] value. This will solve your problem.
I would suggest using a static dataset and bind it to the recordsource of the gridview control. Whenever you wanna edit a record update the dataset simultaneously and rebind it to the gridview control....hope that helps:)
I'm an intern that has never done any web development just so you know where I'm coming from. I'm currently trying to learn asp.NET MVC 3 using devexpress 12.1 tools. I started with a template that had a devexpress gridview in the content area that is linked up to the Northwind db. It works by itself, but when I create a devexpress tab strip and place the gridview inside the second tab I get the column headings, but no data is displayed. When I click on a column heading to sort the data shows up. I'm wanting the gridview to load after I click the tab and not when the page loads. Maybe my callbacks are the problem. My tab strip is using an ajax callback and the gridview is as well for the paging. I have added the model to the TabControlPartial page and passed in the model in the controller for the TabControlPartial action. I've tried looking at the demos at mvc.devexpress.com, but there is nothing that puts the two together. I don't 100% understand passing the model into the view I guess. I know this is simple, but I don't know what to do. Thanks for your help.
Controller (this may be my issue):
public ActionResult LookUp()
{
return View(NorthwindDataProvider.GetCustomers());
}
public ActionResult _TabControlPartial()
{
return PartialView("_TabControlPartial", NorthwindDataProvider.GetCustomers());
}
public ActionResult _GridViewPartial()
{
return PartialView("_GridViewPartial", NorthwindDataProvider.GetCustomers());
}
LookUp View (Index):
#model System.Collections.IEnumerable
#Html.Partial("_TabControlPartial", Model)
Tab Partial:
#model System.Collections.IEnumerable
#Html.DevExpress().PageControl(
settings =>
{
settings.Name = "TabControl";
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Height = System.Web.UI.WebControls.Unit.Percentage(100);
settings.CallbackRouteValues = new { Controller = "Customers", Action =
"_TabControlPartial" };
settings.TabPages.Add(
tabOne =>
{
tabOne.Name = "TabOne";
tabOne.Text = "Start";
tabOne.SetContent(() =>
{
ViewContext.Writer.Write("Start");
});
});
settings.TabPages.Add(
tabTwo =>
{
tabTwo.Name = "TabTwo";
tabTwo.Text = "Customer List";
tabTwo.SetContent(() =>
{
Html.RenderPartial("_GridViewPartial", Model);
});
});
}).GetHtml()
GridView Partial:
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "GridView";
settings.CallbackRouteValues = new { Controller = "Customers", Action =
"_GridViewPartial" };
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Height = System.Web.UI.WebControls.Unit.Percentage(100);
settings.SettingsPager.Visible = true;
settings.SettingsPager.PageSize = 15;
settings.ControlStyle.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
settings.ControlStyle.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
settings.ControlStyle.BorderBottom.BorderWidth =
System.Web.UI.WebControls.Unit.Pixel(1);
//Configure grid's columns in accordance with data model fields
settings.Columns.Add("ContactName");
settings.Columns.Add("Address");
settings.Columns.Add("City");
settings.Columns.Add("PostalCode");
settings.Columns.Add("Phone");
}).Bind(Model).GetHtml()
You're missing the data in the GridView when the tab is opened. When you open the page, the data for the GridView needs to be loaded in the Model that is returned. right now you load the page (in LookUp), but you aren't pushing the data for the grid. whenever any callback occurs, only at that point is the data getting pulled from the database and returned to the screen (notice you only return data in the Callback methods _TabControlPartial and _GridViewPartial). When you sort a column, or filter, etc, then the callback is fired and the data is returned from the server.
The code you have looks correct, but somewhere in the process the Model is losing it's value. the best option is to put a breakpoint in the tab control, the Grid Binding, and the controller and make sure the data you expect is in place when it's bound.
You could "cheat" by putting in a callback when the tab is activated such as:
#Html.DevExpress().PageControl(
settings =>
{
settings.Name = "TabControl";
settings.ClientSideEvents.Init = "TabControl_Init";
...
}).GetHtml()
and in JavaScript have:
function TabControl_Init(s, e) {
GridView.PerformCallback();
}
this way, after the tabs are initialized, the GridView will run a callback, and grab the data correctly. But it would be better to figure out why the data isn't being sent down in the first place by stepping through the code.
I have an aspx page which has the following:
A repeater with a linkbutton in each
The link button has a commandargument of an integer value
A user control
The idea is that when the user clicks on the linkbutton the value of the commandarguement is stored in a List. No problem you may think, however I need the value to be stored in an List in the usercontrol, not in the ASPX page. The List needs to be persisted across postbacks, so it also needs to be stored in the viewstate.
So I created a public property in the user control like so:
public List<int> ImageString {
get {
if (this.ViewState["ImageString"] != null) {
return (List<int>)(this.ViewState["ImageString"]);
}
return new List<int>();
}
set { this.ViewState["ImageString"] = value; }
}
And then I was hoping that from my aspx page I could add a line of code to add a value to the list like so:
this.LightBoxControl.ImageString.Add(value);
The problem I'm getting is that the the value is actually never added to the list. The count is always zero.
I'm sure its just that I've set the property up wrong, but I'm not sure how to right it..
Any help would be greatly appreciated.
Thanks
Al
Your getter is wrong. This is the correct variant:
get {
if (this.ViewState["ImageString"] == null) {
this.ViewState["ImageString"] = new List<int>();
}
return (List<int>)(this.ViewState["ImageString"]);
}
Here you first check whether there is something you need in ViewState already, and if there is no, you add it there. Then you return the item from ViewState - it is guaranteed to be there.
Your solution was bad because it did not place new List<int>() into the ViewState