If I see something like:
if(Request["Email"])
{
}
What does this actually mean? Where is the Email collection member actually being set?
It's retrieving the variable from get/post parameters.
somepage.aspx?blah=1
string blahValue = Request["blah"];
Console.WriteLine(blahValue);
> 1
Even more specificially:
Cookies, Form, QueryString or ServerVariables
http://msdn.microsoft.com/en-us/library/system.web.httprequest_members(VS.71).aspx
See this for example.
Taken from the above link
All variables can be accessed directly by calling Request(variable) without the collection name. In this case, the Web server searches the collections in the following order:
QueryString
Form
Cookies
ClientCertificate
ServerVariables
It retrieves either the submited form values (POST) or the submitted querystring values (GET).
You would generally see it written as either Request.Form["Email"] or Request.Querystring[Email"] instead of just Request["Email"].
Example of Form (POST) method:
On the HTML or ASPX Page:
<form action="SomePage.aspx">
<input type="hidden" name="Email" value="someaddress#email.com" />
<input type="Submit" value="Submit Form" />
</form>
Once the form has been submitted by clicking the Submit Form button you would retrieve the form values using Request.Form["Email"] (or just Request["Email"] for the lazy :))
Just some additions to the posts of the others.
To have things more explicitly you normally use Request.QueryString[...] for getting values from the QueryString, so when a GET request has been done and Request.Form[...] when a POST request is done. Although in the latter case you usually directly access the values of your server controls, since ASP.net uses the ViewState mechanism to load back on your controls when the request comes back from the client.
Related
i wanna to understand difference between viewsate["x"] and __viewstate in view source
ie
in view source page there is view state in hidden control like:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="dO3F9exemRdHoXxGHr"/>
but in c# i can create viewstate like:
viewstate["x"]="Hi";
so what is the difference???
and the string "Hi" where it be saved ? in this hidden or where?
When a page is rendered, it serializes its view state into a base-64
encoded string using the LosFormatter class and (by default) stores it
in a hidden form field. On postback, the hidden form field is
retrieved and deserialized back into the view state's object
representation, which is then used to restore the state of the
controls in the control hierarchy.
That means yes it saved in this hidden field, but it is encoded. Read MSDN article for more information. This quote is from 6.PARSING THE VIEW STATE.
If you have any interest you can parse the ViewState and see his "real values". You can search for view state parser, after research I found this Website
ViewState is a storage method on server side that is persisted on client side. What you're seeing is the two faces of the same coin
You use it on server side doing something like this
Viewstate["x"]="Hi";
And when the response is sent to the client, the ViewState storage is serialized and sent to the client in the form of an input field
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="dO3F9exemRdHoXxGHr"/>
When you set view state using ViewState["x"], it is stored in the hidden field __VIEWSTATE. It is first encoded, however, so you won't see "Hi" in that hidden field.
i have a list of thumbnails for the user can select one of the image.
onclick on the thumbnail open a larger image into a form.
What im trying to do now is send the id of the image selected to my controller.
Note: im using MVC 4.
how can i do that?
someone can help with this pls?
Thanks in advance:
Here is my code:
#foreach (var p in ViewBag.Images)
{
<li>
<a href="~/Files/#p.Name" onclick="swap(this); return false;">
<img src="~/Files/#p.Name"/>
</a>
</li>
}
when selected is going this img tag in my form:
<img id="main" src="" >
using this javascript for this event:
function swap(image) {
document.getElementById("main").src = image.href;
}
what i have to do now?
i trying with <input type="hidden" name="Img_Id" value="Viewbag.??????"/>
to pass this value to my controller??
First, some terminology help: You can't pass a value from the view to the controller action, the view is rendered after the controller action completes.
What you want to do is pass data from the client (web browser) to a controller action, using form fields.
In your javascript swap method, you could set the value of the Img_Id field to be the value for the selected image. When the form is submitted, the Img_Id will be posted as form data, and can be accepted as a parameter in the action.
You can use JQuery (or something else) to perform the client side actions.
Here's an example (not tested though!):
First add the ID as a data attribute on the element:
<a href="~/Files/#p.Name" data-id="#p.ID" onclick="swap(this); return false;">
Then some javascript to save that to form (using jquery here):
function swap(image) {
document.getElementById("main").src = image.href;
$("input[name='Img_Id']").val($(image).data("id"));
}
To pass a value back to your controller, you either need to submit a form, or else make an AJAX request to your controller.
In the first case, you'd need to update the value of your hidden field with javascript, and then either wait for the user to submit the form, or trigger a submit through javascript depending on what your needs are.
If you want to do an ajax request, it would be more or less the same thing, but you don't need a hidden field to store the value.
You could use jQuery in your swap function. See here for the official documentation.
If you chose to use this approach, and assuming you place your JavaScript in a separate file, then make sure you get the path for the action and controller and pass that in too.
var url = #Url.Action("Index","Home");
Therefore you may call: onclick="swap(this.id, url)"
say for instance I have the following button in a form in asp.net mvc 3 app:
<input type="submit" name="command" value="Click me" data-custom="D" />
I know how to get the value from the button.. however do I get the data-custom attr value in an action method? Thank you very much!!
Edit:
I should note that I'm not allowed to use javascript at all since this is a mobile version of the site for devices that do not support javascript..
however do I get the data-custom attr value in an action method?
No you don't. There is nothing in the HTML specification that indicates that data-* attributes should be sent to the server when submitting a form. So if you want to get that value you will need to use javascript. One technique consists in subscribing to the submit event of the form and then automatically injecting a hidden field into that form which will be populated from the data-* attribute of the submit button. This way the value will be sent to the server.
But since I suspect that what you are trying to achieve here is that you have multiple submit buttons and you want to know which button was clicked in your controller action. In this case you could use the following:
<button type="submit" name="btn" value="S">Save</button>
<button type="submit" name="btn" value="D">Delete</button>
...
and then have your controller action take an argument called btn.
But personally I prefer to use separate actions otherwise it makes the controller action very ugly since it will contain lots of if statements. Here's a nice blog post I would invite you to checkout.
A custom attribute is not passed through get or post; only values do.
You can grab the custom attribute value from client side (for example using jQuery .attr() function) and add it to your form data before submitting it.
as far as I know you can't get data directly from data-... . you can write javascript to get this value.
Only the value and the name of the form element are posted within a form and any data-* cannot be passed.
You can consider a workaround using JavaScript. The idea is to so somehow merge the data-custom value to your value attribute.
$("input[type=textbox][data-custom]").each(function(index, value) {
$(value).attr("value", $(value).attr("value") + "$$$" + $(value).attr("data-custom"));
});
And from your action method, use data.split("$$$")[1] to get data-custom.
Hope this helps
I am rendering out a ViewUserControl (.ascx file) in a view:
<% Html.RenderPartial("Comments", Model.Comments); %>
This ViewUserControl shows associated comments on an entry. I would like this control to render out a form as well, so users of my application can contribute.
How would you add a form to a ViewUserControl and handle it's postback?
Just add the form in there the same as you would on any page. In MVC, the form does not postback as such - it simply submits itself and its content (input controls) via HTTP Post to a URL.
Simply create an action in your controller (and hence a URL) which the form will post and do whatever activity is required there...
There is no postaback, like in standard asp.net, there can be only form tag that posts data to some url (controller/action).
Inside your partial user control, write:
<form action="controller/actionname" method="post">
<input type="text" name="inputText" />
<input type="submit" value="Post data to server" />
</form>
In MVC, only input type="submit" triggers form submit. In standard ASP.NET webforms, you can have many Linkbuttons, Buttons, ... but under cover, they all triggers this simple click on input type="submit" through javascript event. One form can post data to only one URL (controller/action), but that can be changed with javascript (as we can see in html source of 'old' asp.net webforms).
then, in controller you can handle post data:
[AcceptVerb(HttpVerb.Post)] // optionally
public ActionResult ActionName(string inputText) ...
Like others have answered already, you simply render a form and handle it's submit with an ActionResult.
For example, if your form (which could be rendered anywhere in your site) was submitting to http://www.yoururl.com/home/save, you would create an ActionResult method named save on the home controller to handle the submit (likely post/get method).
I am interested to know what specifically Page.IsPostBack means. I am fully aware of it's day to day use in a standard ASP.NET page, that it indicates that the user is
submitting data back to the server side. See Page:IsPostBack Property
But given this HTML
<html>
<body>
<form method="post" action="default.aspx">
<input type="submit" value="submit" />
</form>
</body>
</html>
When clicking on the Submit button, the pages Page_Load method is invoked, but the Page.IsPostBack is returning false. I don't want to add runat=server.
How do I tell the difference between the pages first load, and a Request caused by the client hitting submit?
update
I've added in <input type="text" value="aa" name="ctrl" id="ctrl" /> so the Request.Form has an element, and Request.HTTPMethod is POST, but IsPostBack is still false?
Check the Request.Form collection to see if it is non-empty. Only a POST will have data in the Request.Form collection. Of course, if there is no form data then the request is indistinguishable from a GET.
As to the question in your title, IsPostBack is set to true when the request is a POST from a server-side form control. Making your form client-side only, defeats this.
One way to do this is to extend the ASP.NET Page class, "override" the IsPostBack property and let all your pages derive from the extended page.
public class MyPage : Page
{
public new bool IsPostBack
{
get
{
return
Request.Form.Keys.Count > 0 &&
Request.RequestType.Equals("POST", StringComparison.OrdinalIgnoreCase);
}
}
}
In the example that you include in your question, there is no viewstate involved; there is no way for the server to link this request to a previous request of the page and treat them as a unit. The request resulting in clicking the button will look like any other random request coming in to the server.
Generally a you could view a PostBack as a combination of:
HTTP request method equals "POST"
HTTP header HTTP_REFERER equals the current URL
That's not 100% foolproof tho, it does not take into account any state of any kind (which you probably want even if you don't know it) but it is a post, back to the current page.
You could check the headers to see if your input controls are returning a value (using Request.Forms as tvanfosson points out). However, the really big question is why you would not want to add runat=server. The entire page processing edifice implemented by ASP.NET (except MVC) depends on processing the page output through the server to set up the appropriate client-side code for callbacks, etc.