How to save a dictionary value in a viewstate? - asp.net

I have a questions and answers page when some questions gets hidden and some gets visible depending upon the predecessor answers. at the end i need all the answers.
I am trying to use dictionary for this. I add answers with a key on a changed event of each control. but none of the answers are saved when i move to next section as i am hiding the previous sections.
I am trying to save it in a viewstate and add the values so that my values persists in the dictionary..
Any ideas?
Here is the code:
Dictionary<String, String> Answers;
protected void Page_Load(object sender, EventArgs e)
{
Answers = (Dictionary<String, String>)ViewState["Answers"];
ViewState["Answers"] = Answers;
}
protected void rdb_study_popul_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["StudySamplepopulation"] = rdb_study_popul.SelectedValue.ToString();
Answers.Add("StudyPopulation", ViewState["StudySamplepopulation"].ToString());
}
Right now, Answers will be empty if I move to next section.
Any help would be greatly appreciated.
i am getting null reference error Object reference not set to an instance of an object.
Public partial class
{
Dictionary Answers;
protected void Page_Load(object sender, EventArgs e)
{
Answers = ( Dictionary<String, String>)ViewState["Answers"];
}
protected void rdb_studysubj_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["StudySubjectAnimal"] = rdb_studysubj.SelectedValue.ToString();
studysub_popul.Visible = true;
Answers.Add("StudySubjectAnimal", ViewState["StudySubjectAnimal"].ToString());
ViewState["Answers"] = Answers;
}

You do not need to update the ViewState in page load, because it has not changed yet, so remove the assignment of ViewState in your Page_Load and do this instead:
protected void Page_Load(object sender, EventArgs e)
{
// Only read the value from ViewState, do not update it here
Answers = (Dictionary<String, String>)ViewState["Answers"];
}
Now in you event handler, when you are done adding to the Answers, then you should update your ViewState value, like this:
protected void rdb_study_popul_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["StudySamplepopulation"] = rdb_study_popul.SelectedValue.ToString();
Answers.Add("StudyPopulation", ViewState["StudySamplepopulation"].ToString());
// Now that you are done altering the Answers, save the updated value to ViewState
ViewState["Answers"] = Answers;
}
UPDATE:
You need to check if ViewState is null or not, like this:
Dictionary<String, String> Answers = new Dictionary<String, String>();
protected void Page_Load(object sender, EventArgs e)
{
// Is there anything in ViewState?
if (ViewState["Answers"] != null)
{
// Yes, but only read the value from ViewState, do not update it here
Answers = (Dictionary<String, String>)ViewState["Answers"];
}
}
Note: I changed the declaration of the Answers dictionary to also include instantiating it, so that it will not be null.

Related

Is using OnPropertyChanged(string.Empty); a practice to avoid?

We have OnPropertyChanged(string.Empty); in quite a few places in our Xamarin.Forms application. In general I feel like we shouldn't be saying "Hey, notify everyone that all the properties on this object have changed."
An example of where we do this is in some data syncing event handlers in a view model that inherits
private void OnSyncEnding(object sender, EventArgs e){
SyncItem = syncService.Value.SyncState;
OnPropertyChanged(string.Empty);
}
private void OnSyncStarting(object sender, EventArgs e){
SyncItem = syncService.Value.SyncState;
OnPropertyChanged(string.Empty);
}
private void OnSyncFormSuccessful(object sender, EventArgs e){
SyncItem = syncService.Value.SyncState;
OnPropertyChanged(string.Empty);
}
My question is: How much work does this actually trigger and when is using OnPropertyChanged(string.Empty); the correct thing to do instead of calling OnPropertyChanged("SomeProperty") for all the properties required?

Why is my UserControl's ViewState partially saved?

I have a user control that makes substantial use of this.ViewState["Key"] = SomeValue. Most of it is loaded from my Page_Init():
protected void Page_Init(object sender, EventArgs e)
{
if(!IsPostBack)
{
ViewState["Blahblah"] = LoadSomeValue();
}
}
The rest are set at various points.
But for some reason it's unavailable on subsequent postbacks. I overrode SaveViewState() to check, and only like three of them are saved!
protected override object SaveViewState()
{
List<object> viewStateObjectsBefore = ViewState.OfType<object>().ToList();
object ret = base.SaveViewState();
List<object> viewStateObjectsAfter = ViewState.OfType<object>().ToList();
GC.KeepAlive(viewStateObjectsBefore);
GC.KeepAlive(viewStateObjectsAfter);
GC.KeepAlive(ret);
return ret;
}
Both viewStateObjectsBefore and viewStateObjectsAfter contain 10 key/value pairs, but ret only contains three!
Added: Moving the initializations to Page_Load() is not an easily available option, because the initializations must be done before the parent's Page_Load() executes.
Adding a call to SetDirty() at the end of my Page_Init() solved the problem:
protected void Page_Init(object sender, EventArgs e)
{
if(!IsPostBack)
{
ViewState["Blahblah"] = LoadSomeValue();
//Looks like the ViewState is not yet "tracking" changes before Page_Load.
//The items have to be marked as "dirty" manually so they'll be included by SaveViewState().
ViewState.SetDirty(true);
}
}

Update a label in server side in ASP.Net after Button Click

I want to update my label content when the user submits a form but it doesn't get updated. Although I have put it in if (!IsPostBack) condition in form load It doesn't show the changes. The only solution that I came up with was defining a counter and increase it in button_click event and check it before label update in !IsPostBack condition. Which is working fine with that.
Is there any other way to update the label text?
Here is my solution:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (count > 0)
lblSuccessMsg.Text ="A Message!";
count = 0;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Save();
count = count + 1;
}
please update your label code outside of !IsPostBack evnt and inside a pageload.
Hard to tell but by the sounds of it you have a submit button and the onclick needs to update this label, something like this should work. I'm using viewstate but session would work here, as would a redirect to the same page with a querystring parameter. Not sure if I've understood your question correctly though.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if(Viewstate["updateLabel"] == "true")
{
lblYourLabel.Text = "I'm updated now!";
Viewstate["updateLabel"] = "";
}
}
}
protected void btnYourButton_Click(Object sender, Eventargs e)
{
ViewState["updateLabel"] = "true";
//Do other stuff here if you want
}

ASP.NET (GridView): GridView1.Rows[e.RowIndex].Cells[1].Text returns the original value not the value that I just entered

Editing Method:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
}
Updating Method:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int _selectedRowIndex = e.RowIndex;
int _ameintyId = (int)GridView1.DataKeys[_selectedRowIndex].Value;
string updatedAmenity = GridView1.Rows[_selectedRowIndex].Cells[0].Text;
}
N.B: and a strange thing that I noticed, when I click edit it reloads the page but won't edit the row, so I click it again and it works .. and this happen everytime, it's not an exception or something!
Edit
First of all I'm using a BoundField .. I figured out that when I add a DataKey it created a new field for it which is the ID and that what caused the problem! so I just changed the 0 to 1 .. but now I'm facing a problem that the cell Text property returns the original value not the new value!
First Issue: To get the value I just entered instead of the original value
Updating Method: Used e.NewValues property
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int _selectedRowIndex = e.RowIndex;
int _ameintyId = (int)GridView1.DataKeys[_selectedRowIndex].Value;
string updatedAmenity = e.NewValues[0].ToString();
}
Second Issue: Clicking twice to get the edit button to work
Editing Method: I just called my method that binds my grid
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
AmenitiesGridDataBind();
}
Thanks for offering your help =)
string updatedAmenity = e.NewValues[0].ToString();

how to display the mark sheet on the next page using ASP.NET?

i want to creat a web page that uses radiobuttons in a multiple choice quetions, but i want to do is to use a submit button to return the results to the next page with the mark sheet, so can you please help me with that. how to display the mark sheet on the next page using ASP.NET
Use Session state.
For example,
protected void Button1_Click(object sender, EventArgs e)
{
Session["key"] = TextBox1.Text;
Response.Redirect("marksheet.aspx");
}
Code in Page_Load of marksheet.aspx,
protected void Page_Load(object sender, EventArgs e)
{
if (Session["key"] != null)
{
object val = Session["key"];
...
}
}

Resources