Say I create a static .html page. Next I build a form with a bunch of input boxes. Then I decide I want to post all that form data to another page, call it process-form-data.aspx. My question is, since I posted the form data to an .aspx page, how can I use C# in the code behind screen to grab all that data?
I tried the following first:
NameValueCollection nvc = Request.Form;
string valTextBox1;
if (!string.IsNullOrEmpty(nvc["txtBox1"]))
{
valTextBox1 = nvc["txtBox1"];
Response.Write(valTextBox1);
}
And then I tried:
valTextBox1 = Request.Form["txtBox1"].ToString();
Response.Write(valTextBox1);
But neither method seems to work. I can only get those two methods to work if I submit the form using the runat="server" attribute on an .apsx page.
I'd like to avoid passing the variables through the URL.
Thanks for any help.
Thanks for all the suggestions! I thought when a form was submitted, the default method was to POST the data; turns out it's GET. (http://www.w3.org/TR/html401/interact/forms.html)
I just added the following attribute to the form tag: method="post".
<form action="process-form-data.aspx" method="post">
<input type="text" name="txtBox1" />
</form>
Both methods of collecting the form data mentioned in the original post work fine.
Related
I am working for a project which has web garden scenario and cannot keep any data in session/inmemory.
The asp.net page opens from Appian(bpm tool) and we pass id through query string.
Now, client is asking me to hide the query string parameter after reading it. But, in that case say, landing page is http://a.aspx?id='123' and after reading that value we have to redirect to b.aspx without exposing the id(query string).
Please suggest me a suitable way to achieve this. I am not really getting any idea for this.
you can add key/value pairs to the header, it won't be visible in the querystring.
HttpContext.Current.Response.Headers.Add( key, value);
and
string headerVal = HttpContext.Current.Request.Headers[key];
You can use session variables on the server side or http Post instead of GET.
Session["id"] = id;
And on load of b retrieve it.
To use Post you can use a hidden field and a form.
//You can set it like this
<form name='IdForm' action='b.aspx' method='post'>>
<asp:HiddenField id="WhateverId" runat="server" value='<%= Request.QueryString["whateverID"] %>' />
</form>
On redirect use javascript to post
function Redirect() {
document.forms["IdForm"].submit();
}
You must use this js script wherever the redirection happens.
And finally on b.aspx code behind
HttpContext.Current.Request.Form["WhateverId"]
I have a charts program that works in js, but I need to update excels with the data using c#. So, what I've done so far is to create hidden input fields whose values are updated with the js variable:
<input type="hidden" name="baselineInput" id="baselineVariable" />
<input type="hidden" name="goalInput" runat="server" id="goalVariable" />
<input type="hidden" name="currentInput" runat="server" id="currentVariable" />
//do some things here
var MTDGauge = new Array(5,5,5);
document.getElementById("baselineVariable").value = MTDGauge[0];
document.getElementById("goalVariable").value = MTDGauge[1];
document.getElementById("currentVariable").value = MTDGauge[2];
The problem I'm having is reading these values back to the c# variable. Here's what I've tried (placed after the code above):
List<string> OverallData = new List<string>();
OverallData.Add(Request["baselineInput"]);
OverallData.Add(Request["goalInput"]);
OverallData.Add(Request["currentInput"]);
This is just adding null values (assuming so because the c# is loading before the javascript and the initialized values for the text fields are null?). I thought of creating a c# function that could be called using the onchange option in the input field, but that didn't get me anywhere. Is there something I'm missing? Do I have to do a post?
Thanks
Yes, to get your data back to the server (where your C# is running) you need to send it back.
POST is one way, or GET to add the values to the query string.
Javascript is only running in the browser, until you send something back to the server, your ASP.NET app will not have any information.
Of course, if you want to do it asynchronously you could use jQuery.ajax to send the data to a server URL without refreshing the whole page.
I have a C# MVC application and a <form> in my page.cshtml file. In that form I have <input type="text" ... /> elements. If I submit this form I only get the values in Response.Params or Response.Form from the inputs where I changed the value manually (i.e. Entered the text box then typed something).
If I change the value with jQuery, $('#myInput').val('some value'); this does not count as a change in the input's value and I do not get myInput's value when I submit the form.
Is there any way to make sure all inputs are submitted? If not then is there a good workaround for this, maybe in some event that occurs before my model gets bound? I need to know all the input values from the form when submitted whether they changed or not.
Some additional info:
The form and other values are getting submitted correctly and I am receiving my model when the POST action is called in my controller.
The real issue is when my model is being bound. It is being created and bound with all values except the one not being submitted because it is not in the Request.Params collection.
I have only ever seen this behaviour when a field is disabled. Due to this, I commonly have a javascript function that handles the form submission and re-enables them on submit, this way the correct values get sent to the server.
Something like this does the trick for me (NOTE: I am using JQuery):
$(document).ready() {
$("#ButtonSubmit").click(SubmitForm);
}
function SubmitForm(e) {
e.preventDefault();
//ensure fields are enabled, this example does text and checkbox types
$("[type='text']").attr("disabled", false);
$("[type='checkbox']").attr("disabled", false);
//submit the form
document.forms[0].submit();
}
I am unaware of any easier way to do this, it would be nice if you could 'flag' something that instructs all fields to be submitted. But I don't know if this exists, maybe somebody else can offer a better solution.
EDIT: It appears that disabled fields not submitting is just the nature of HTML, and is not something that is tied to MVC.
It seems that if you make the fields readonly instead of disabled then the values will still submit. However, with this approach you lose the 'disabled' styling. The exception to this rule is select control, it seems this will not submit under readonly either. More information on this can be in this question
Try using the razor helper to build the form tag.
#using(Html.BeginForm()) {
..
// make sure this is a submit button
<input type="submit" value="Save" />
}
In your controller action post method make sure you decorate it [HttpPost].
e.g.,
[HttpPost]
public ActionResult Edit(YourModel model) {
}
I have this:
<form id="import_form" method="post" enctype="multipart/form-data" action="/Blah/Blah">
<input type="file" id="fileUpload" name="fileUpload"/>
<input type="submit" name="submit" value="Import"/>
</form>
$('#import_form').submit(function () {
...
});
Here is the c# method:
[AcceptVerbs(HttpVerbs.Post)]
public string Blah(HttpPostedFileBase fileUpload, FormCollection form)
{ ... }
I want when Blah finishes executing a javacript code to start executing. How to do this?
The submit event is called before it.
This depends on how the form is being submitted.
If you're submitting the form via AJAX then you can execute some JavaScript in the handler for the response. However, given that there's a submit button, I'm assuming for the moment that you're not doing this via AJAX and are instead posting the whole page to the server and rendering a response.
In this case, to execute some JavaScript after the form post, you're going to need to render that JavaScript in the response from the server as part of the next page. When the server constructs the view, include the JavaScript you want to execute in that view.
Keep in mind the request/response nature of the web. When something on the server executes, the client is unaware of it and disconnected from it. The end result of any server-side processing should be an HTTP response to the client. In the event of submitting a form or clicking a link or anything which results in a page reload, that response is in the form of a new page (view). So anything that you want to do on the client after the server-side processing needs to happen as part of that response.
Edit: I just noticed that Blah is returning a string. Is this even working for you? How does the form submit result in a new view? Or am I unaware of a feature in ASP.NET MVC?
This is what I did in the end.
My form returns the exact same view with whom it was called.
I add a ViewData in the Blah method.
In the view, in the $(function()) event I check if ViewData has a value, I execute the javascript code.
Assume I have on a page an article with the possibility to comment it. I have a submit form that submits via ajax and the OnComplete javascript method intercepts the result of the form submit.
Each comment is smth like:
<div class="text">
<p class="details">
User Always_Dreaming at 01/01/2009 - 11:13:52 </p>
<p>Here goes my text :D</p>
</div>
I made an .ascx file from it, and I do tml.RenderPartial foreach comment. Now the question is how can I use this .ascx control to output the inserted content to the OnComplete method from client side.
PS. I want to use this approach and not to serialize the Comment object and to return the serialized data, take it wioth my js code and generate on the fly the html with data from the deserialized Comment object.
What you need to do is use the PartialViewResult from the action that's invoked by your javascript call. The client side code can append it to the html using something like the jQuery append or html method calls.
for those who are interested, I found a sample :)
here