passing values using viewstate across postback in multiview - postback

I have a multiview and have 2 views inside it. I am going to paste a sample code.
<asp:MultiView ID="MultiView1" ActiveViewIndex="0" runat="server">
<asp:View ID="View1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="view1" />
<asp:Label ID="Label2" runat="server" ></asp:Label>
</asp:View>
<asp:View ID="View2" runat="server">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="view2" />
</asp:View>
</asp:MultiView>
I want the value in txtbox1 to be there in postback. Though multiviews maintain state i do response.redirect to pass querystring to view2. Since i do postback i cannot use the value in txtbox1(in view1), in view2. The value in txtbox1 becomes null during postback. I tried the following code
Public Partial Class viewstatetest
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.IsPostBack()) Then
MultiView1.ActiveViewIndex = 0
Else
TypedPassword = TextBox1.Text
TextBox1.Attributes.Add("value", TypedPassword)
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
MultiView1.ActiveViewIndex = 1
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
MultiView1.ActiveViewIndex = 0
Label1.Text = TextBox1.Text
Response.Redirect("viewstatetest.aspx")
End Sub
Public Property TypedPassword() As String
Get
If (ViewState("TypedPassword") IsNot Nothing) Then
Return CStr(ViewState("TypedPassword"))
End If
Return ""
End Get
Set(ByVal value As String)
ViewState("TypedPassword") = value
End Set
End Property
End Class
When the page loads for the first time, i type something in txtbox1 in view1 and click on the button, view2 is loaded and i have a code that gets the value of the txtbox1 and writes the value inlabel1 in view1. And when i do response.redirect the textbox1 becomes null and view also become null.
Why there is no value in viewstate?
Thanks!

Asp.Net viewstate is very different from normal get/post browser requests in other systems such as Rails, PHP, or even Asp.Net MVC.
Here is what is going on in your scenario:
User's browser does HTTP get on page for first time. This is not a postback.
User fills in TextBox1 and clicks Button1. This is a postback (HTTP post).
On the server, the information in the encrypted hidden __VIEWSTATE variable is unpacked and compared with the new values for TextBox1 and Button1 according to the post data in the request.
Asp.Net identifies state changes and fires events in your server code. This results in the change of the active view index to 1.
The browser now receives the page with View2 shown.
User hits Button2. This is a postback (HTTP post).
The server goes through the same process as before comparing viewstate to post data and fires the Button2 click event.
Your code now does something different. When you do a Response.Redirect, the server does not send back the page with new viewstate. You are sending a short header without the preserved viewstate information in the hidden form variable. The redirect forces the browser to immediately do an HTTP get operation to the url specified. THIS IS NOT A POSTBACK and the view state has been lost. It is exactly the same scenario as the first HTTP get from the user's browser in step 1.
I hope this helps. I think it is safe to admit that Microsoft has recognized the drawbacks from their viewstate model in Asp.net. It makes it quite difficult to implement sexy, modern ajax applications where the browser is maintaining most of the application state and just wants to make small requests for new data from the server. I think this is one of the primary motivations for abandoning the viewstate model in Asp.Net MVC.

Related

Handling FormView databinding event on MasterPage from ContentPage

Hoping this is simple. My goal is to have my masterpage carry a formview which can bind data retrieved based on variable held in my content page, or in the alternative based on variable held as a session variable. As a test, I set up a masterpage including a formview id=testerFV. There is also a label on page id=receiveno. From the masterpage I made a public property:
Public ReadOnly Property testerFVx() As FormView
Get
Return Me.testerFV
End Get
End Property
Similarly, a public property for the receiveno label.
I added <%# MasterType VirtualPath="~/masterpages/testmaster.master" %> to my content page. On my content page, I included a button titled testit. Backcode for the testit button is this:
Protected Sub testit_Click(sender As Object, e As System.EventArgs) Handles testit.Click
Dim tester1FVx As FormView = Master.testerFVx
If tester1FVx IsNot Nothing Then
Master.receivenox.Text = "testerfvx is not nothing"
Else
Master.receivenox.Text = "testerfvx is nothing"
End If
End Sub
The label displays "testerfvx is nothing" so apparently the receiveno label is findable in the masterpage through the public property, but I'm not finding the formview.
In another quick test, I tried binding the formview on the masterpage on the page load with a dummy collection like this:
Protected Sub page_load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim thisthing As New List(Of fakenumbers)
Dim thisone As New fakenumbers
thisone.Thisnumber = 42
thisthing.Add(thisone)
testerFV.DataSource = thisthing
testerFV.DataBind()
End Sub
But I get an object not found error.
So: bottom line, how do I access a formview located on a masterpage from an event happening on my content page and using variables currently held on the content page. Also, if I include a testerFV_databound handler in the master page, will it respond correctly when I've triggered the databinding event from my content page?
Any help would be appreciated. Thanks!

how to use server side button click event in mvc4?

I have to make a textbox somewhere in the page and a button using ASPX View Engine.That page already contains partial views. User will enter his data (code) on textbox and at button click, server code will manipulate that data and show an alert or message that data is processed. How to do that in mvc4?
I have found that we can write server script in page like
<script runat="server">
Protected Sub Button1_Click(sender As Object, e As EventArgs)
ScriptManager.RegisterStartupScript(Me, [GetType](), "showalert", "alert('Message Sent');", True)
End Sub
Private Sub DataProcess(ByVal Data As String)
'Code to check data
End Sub
</script>
You can create a separate Ajax Form ccontaining only this button and the textbox. So you will call an Action in a certain controller then this Action will return a string or a Json. And via an UpdateTargetId property you can display a dialog box. Giving you the code is difficult because I don't know the structure of your code. You can aslo write the Ajax call using Jquery.
This link can help you

Passing and Storing objects between Pages

I'd like some advice on this issue. Basically, I have 2 pages (for simplicity sake), and the second page is completely dependent on the first page.
So lets say the main page is a search page, and the second page is a view page.
The site works off XML requests, and the ultimate aim is to keep the XML requests to a minimum as each request is a little slow. I considered using Sessions, but I've had some problems in the past with sessions being mixed between users randomly which i only manage to curb by changing the recycle process in IIS to a very small time frame, so I'm wondering if there is any other way. I've tried TempData, but that expires after one request, so a page refresh on the view page doesn't seem possible. (or is it?)
Anyways, we have the Search page that has, say, 5 attributes that are required by the View page, but only 2 are needed to make the XML request on the view page.
e.g.
Search Page Contains:
ID,
Name,
City,
Email,
Height
View Page needs the following from the Search page to complete the xml request:
ID,
Name,
Email
View Page displays all the information from the search page, plus everything in the XML response.
The link i have in the search page only has the ID in the url, so name and email are required for the XML request on the second page some how. Not sure if it's possible without sessions?
What i've tried is:
Store the search results in TempData. That way, when someone clicks the 'View' link (View), the View page loads the search results like so:
var viewPage = SearchResults.Where(w => w.ID == id).FirstOrDefault();
The ViewModel then renders the page by grabbing the Name and Email from viewPage, making an XML request, and displaying the response, along with other required details from viewPage.
It works as expected with tempdata. Data only persists on the first request, dies on a page refresh. Sessions is the alternative, but is there any other?
(sorry for the wall of text :)
Why not using more standard techniques like a <form> tag in the search page pointing to the controller action that will perform the search:
#using (Html.BeginForm("search", "somecontroller", FormMethod.Get))
{
... some input fields for your search criteria
<button type="submit">Search</button>
}
and then you will have the Search controller action:
public ActionResult Search(SearchModel model)
{
var results = ....
return View(results);
}
I've used GET method on the form which allows the user to bookmark the results page and come back to it later.

How to perform PostBack operation in ASP.NET MVC?

In mvc the page is not get post back as in asp.net then how can we perform postback operations in asp.net mvc2. for ex how to perform particular action when someone selects a chech box?
Thanks in Advance
The mechanism behind the postback model in WebForms is called HTTP POST. This is how user input is communicated back to the server.
You can do it manually. Attach a JavaScript handler manually to the checkbox "onclick" event and perform a POST request to some url. There, this request will hit some controller action where you do what you want. For example, update the model (check/uncheck the checkbox) and return the same view from which the POST originated. The view will now show the different state for the checkbox.
The WebForms mechanisms do pretty much the same, though these things are abstracted away from you. With ASP.NET MVC you'll need to learn how to do it on your own (which is always a good thing).
Your MVC Action method on your Controller somewhat is your 'PostBack' handler.
Start with a simpler example; a simple HTML form post:
<form action="/MyController/MyAction" method="post">
<input type="text" name="myName" />
<input type="submit />
</form>
Now in your controllers action you can get the posted values and perform your tasks. When done give the browser back what it needs:
public class MyController: Controller
{
public ActionResult MyAction(string myName)
{
// Do something with myName
return new ContentResult { Content = "Hello " + myName };
}
}
As for a checkbox, it is different. You need to learn Javascript (jQuery is the most used library to use with that) and post the action using that. For example you can wire up to the check box 'onclick()' event and perform an XHR - a browser specific Javascript operation, post (you can use jQuery for that too) to your controller.
So you need to start thinking differently than webforms abstractions and get involved with HTML, HTTP and Javascript.
you can Put this inside an MVC Razor page:
if (Request.HttpMethod=="POST") {
}

Mapping individual buttons on ASP.NET MVC View to controller actions

I have an application where I need the user to be able to update or delete rows of data from the database. The rows are displayed to the user using a foreach loop in the .aspx file of my view. Each row will have two text fields (txtName, txtDesc), an update button, and a delete button. What I'm not sure of, is how do I have the update button send the message to the controller for which row to update? I can see a couple way of doing this:
Put each row within it's own form tag, then when the update button is clicked, it will submit the values for that row only (there will also be a hidden field with the rowId) and the controller class would take all the post values as parameters to the Update method on the controller.
Somehow, have the button be scripted in a way to send back only the values for that row with a POST to the controller.
Is there a way of doing this? One thing I am concerned about is if each row has different names for it's controls assigned by ASP.NET (txtName1, txtDesc1, txtName2, txtDesc2), then how will their values get mapped to the correct parameters of the Controller method?
You can use multiple forms, and set the action on the form to be like this:
<form method="post" action="/YourController/YourAction/<%=rowId%>">
So you will have YourController/YourAction/1, YourController/YourAction/2 and so on.
There is no need to give different names to the different textboxes, just call them txtName, txtDesc etc (or even better, get rid of those txt prefixes). Since they are in different forms, they won't mix up.
Then on the action you do something like
public ActionResult YourAction(int id, string username, string description)
Where username, description are the same names that you used on the form controls (so they are mapped automatically). The id parameter will be automatically mapped to the number you put on the form action.
You can also have multiple "valid-named" buttons on the form like:
<input type="submit" value="Save" name="btnSave" id="btnSave"/>
<input type="submit" value="Delete" name="btnDelete" id="btnDelete" /
and than check to see what submit you have received. There can be only one submit action sent per form, so it is like all the other submit buttons did not actually existed in the first place:
if ( HttpContext.Request.Form["btnDelete"] != null ) {
//Delete stuff
} elseif ( HttpContext.Request.Form["btnSave"] != null ) {
//Update stuff
}
I also think that you can implement a custom ActionMethodSelectorAttribute like here http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx (also listed above) to have cleaner separated code.
As rodbv said you want to use seperate <form> elements.
When you are using Asp.Net MVC or classic html (php, classic asp, etc) you have to forget the Asp.Net way of handling button presses. When a form is posted back to the webserver all the server knows about is simply "the form was sent, and contained the following input elements".
Asp.net (standard) adds a wrapper round many of the standard html postback actions using javascript (the __doPostback javascript function is used almost everywhere) and this adds information about which input element of the form caused the postback and delivers it to the server in a hidden form variable. You could mimic this behavior if you really so desired, but I would recomend against it.
It may seem strange 'littering' a page with many <form>'s, however it will mean that the postback to the server will be lighter weight and should make everything run that little bit faster for the user.

Resources