I'm trying to capture the URL submitted when the page loads. When the page loads, it's appended with provided parameters to give me information i need save off. The issue is when I have the user fill in form fields and submit, the URL contains the handler method. What seems obvious is that I need to capture the URL before the form is submitted. I'm not familiar enough w/ Razor to understand if there's an event that fires on load, or how to accomplish this. Is there something simple like a page load event? Thanks!
1) Starts as: https://localhost:44384/sign
2) On submit takes the handler name: https://localhost:44384/Sign?handler=SubmitAndRedirect
<form method="post">
First name:<br>
<input type="text" name="firstname" autocomplete="on" maxlength="10" required><br>
Last name:<br>
<input type="text" name="lastname" autocomplete="on" maxlength="10" required><br>
Employee number:<br>
<input type="text" name="empnum" maxlength="10">
<br>
<br>I agree to the terms above:<br>
<input type="checkbox" name="check" required>
<button type="submit" asp-page-handler="SubmitAndRedirect">Submit and Redirect</button>
</form>
public ActionResult OnPostSubmitAndRedirect()
{
//Capture Form Data and Push to SQL DB
var firstname = Request.Form["firstname"];
var lastname = Request.Form["lastname"];
var empnum = Request.Form["empnum"];
bool isValidUser = ValidateUser(empnum, lastname);
if (isValidUser == true)
{
WriteToDB(firstname, lastname, empnum, url);
return Redirect(hardcoded);
}
else
{
return Redirect("/sign");
}
}
Model binding features of MVC might be what you're looking for. Take a look at this article.
See how it uses the EmployeeViewModel class and how the form gets posted to the action.
There is no protected void Page_Load(object sender, EventArgs e) in MVC as in Web Forms that I'm aware of.
Also check out jQuery's submit handler. Maybe this can allow you to capture some information and process it before submitting.
Thanks all. I was able to resolve adding a property on the C# side and then capture the request before the form was submitted by setting the property outside the form using inline code between paragraph tags.
<p>
#{
var QS = Request.QueryString.Value;
JT.query = QS;
}
#*<h1> #JT.query</h1>*#
</p>
Related
I have a list In my view. For each row, I view button and I am passing Id value as hidden. But when I click any button it is passing wrong hidden value to the controller. Always it passes the first-row hidden value to the controller.
View:
#foreach (var list in Model)
{
<div>
<div > #( ((int)1) + #Model.IndexOf(list)).</div>
<div >#list.details</div>
<div class="col-md-2 row-index">
<button class="btn btn-link" type="submit" name="action:view" id="view">View</button>
<input type="hidden" name="viewId" id="viewId" value="list.WId" />
</div>
</div>
}
Controller:
[HttpPost]
[MultipleButton(Name = "action", Argument = "view")]
public ActionResult ViewDetail(string viewId)
{
return RedirectToAction("ViewDetails");
}
To get all values you need to change the input value type in your controller to array of strings.
I hope that this solution can help you
[HttpPost]
[MultipleButton(Name = "action", Argument = "view")]
public ActionResult ViewDetail(string[] viewId)
{
return RedirectToAction("ViewDetails");
}
if you want to get the exact value you need to duplicate the form within your foreach
in this case you should write somthing like this :
#foreach (var list in Model)
{
<div>
<div > #( ((int)1) + #Model.IndexOf(list)).</div>
<div >#list.details</div>
<div class="col-md-2 row-index">
<form ... > // complete your form attributes
<button class="btn btn-link" type="submit" name="action:view" id="view">View</button>
<input type="hidden" name="viewId" id="viewId" value="list.WId" />
</form>
</div>
</div>
}
Note : You should delete the global form
You should have one form for each row. then you submit that row.
Otherwise as you state it passes first value.
You are setting each value to the same element ID (which is invalid anyway) and name. When you submit your form (which would be more helpful to fully answer your question) it is finding the first element that matches that criteria and submitting it.
There are multiple ways to resolve this such as the already mentioned form per entry but the other preference would be to modify you button to a div and add a click handler to pass the specific value to a js function which would then submit to the controller. Its a preference choice regarding how tightly coupled you want your front end. But the main problem is your element naming convention.
I want to send POST request to AdminController. But when i watch it in debugger, the request is GET.
<form method="post">
<input type="button" formmethod="post" onclick="location.href='#Url.Action("Index","Admin",new {rowID = #p.ProductID})'" value="Delete"/>
</form>
Because you wrote code to do a GET request on the submit button click !
onclick="location.href='#Url.Action("Index","Admin",new {rowID =
#p.ProductID})'"
Here you are setting the location.href value to the /Admin/Index and it will be a new GET request.
If you want to post, simply remove the onclick event on the button. If you want to send the ProductID value, you can keep that in a hidden input field inside your form and when you click submit the value of this form element will be also submitted.
#using(Html.BeginForm("Index","Admin"))
{
<input type="hidden" name="rowID" value="#p.ProductID" />
<input type="submit" value="Delete"/>
}
Assuming your HttpPost Index action method of AdminController has a parameter with same name as the input name to accept the productId.
[HttpPost]
public ActionResult Index(int rowID)
{
// to do : Return something
}
I am not quite sure how to attack this, basically I have two html fields in my aspx page:
<input type="text" name="fname" />
<input type="text" name="lname"/>
Now i would like to populate them from the server side when the page loads based on some data collected from the database, basically this data is stored in two properties
public string FirstName { get; set;}
public string LastName {get; set;}
How can I pass the value from such properties into the html inputs On_Load ?
I would appreciate the help.
Here is one way, assuming Webforms:
<input type="text" name="fname" value="<%:FirstName%>" />
<input type="text" name="lname" value="<%:LastName%>" />
If using .NET before 4.0, replace the <%: with <%=.
Another option is to change the input types to be runat="server" and assigning the values directly on the server side.
Alternatively add runat="server" to your elements, then you could do something like
fname.Value = FirstName;
lname.Value = LastName;
The info I was looking for was like this:
protected void Page_Load(object sender, EventArgs e)
{
address.Value = Request.QueryString["lat"];
address1.Value = Request.QueryString["long"];
}
takes values from the URL string and puts them in an HTML input="text"
http://localhost:64375/Map.aspx?lat=detroit&long=windsor
Enter Address A: <input runat="server" name="address" id="address" type="text" />
Enter Address B: <input runat="server" name="address1" id="address1" type="text" />
thanks Ash and Oded for the combined answer
I have a form in my asp.net mvc view as follow:
<%using (Html.BeginForm("SearchBorrowed", "Admin", FormMethod.Get))
{ %>
<%: Html.TextBox("searchTerm", Request.QueryString["searchterm"])%>
<input type="submit" value="Search" />
<br />
Is Returned :
<%:Html.CheckBox("IsReturned")%>
<%} %>
and here is the 'SearchBorrowed' action:
public ActionResult SearchBorrowed(bool IsReturned=false, string searchTerm = null)
{
IEnumerable<BorrwoinfInfo> bs;
//...Get from repository
return View(bs.ToList());
}
and finally routing settings :
routes.MapRoute(
"SearchBorrowed", // Route name
"{controller}/{action}/{*searchTerm}", // URL with parameters
new
{
controller = "Admin",
action = "SearchBorrowed",
searchTerm = UrlParameter.Optional
} // Parameter defaults
when I submit the form without checking 'IsReturned' Checkbox,
it returns result and the url gets as follow :
.../SearchBorrowed?searchterm=&IsReturned=false
But when I check IsReturned' Checkbox, the urls gets like this:
.../SearchBorrowed?searchterm=s&IsReturned=true&IsReturned=false
Why there is two IsReturned in above url ?!
How Could I fix this ?
Why there is two IsReturned in above url ?!
Because the Html.CheckBox helper generates an additional hidden input field with the same name as the checkbox. If you look at the generated HTML you will see that the helper generated the following 2 input fields:
<input type="checkbox" name="IsReturned" id="IsReturned" value="true" checked="checked" />
<input type="hidden" name="IsReturned" id="IsReturned" value="false" />
This is by design. This helper is intended to be bound to a boolean property on your view model. When a checkbox field is not checked no value is sent to the server, so if there was not no hidden field you wouldn't be able to bind it to a boolean field.
If you don't want this hidden field you could either write a custom helper or generate the checkbox field manually.
I'm trying to allow a web form to use a PayPal buy it now.
The relevant page is here.
Based on which radio button a user selects, depends on which paypal button they are "redirected" to.
The subscriptions are easy - they are just a simple redirect.
The last option, requires a user select a venue.
For this, i require to use the form below:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="10956105">
<table>
<tr><td><input type="hidden" name="on0" value="Venue">Venue</td></tr><tr><td>
<input type="text" name="os0" maxlength="60"></td></tr>
</table>
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
But of course, I want to do it without using that form.
What I have so far is:
if (singleOneOff.Checked)
{
paypalForm.Text = getPaypalForm(venueSelect.SelectedItem.Text);
var strJS = getPayPalPostJS("_xclick");
paypalJs.Text = strJS;
var xxx = "dd";
}
This determines if that particular radio button was ticked.
getPaypalForm
private String getPaypalForm(string venue)
{
StringBuilder strForm = new StringBuilder();
strForm.Append(#"<form action=""https://www.paypal.com/cgi-bin/webscr"" name=""_xclick"" method=""post"">");
strForm.Append(#"<input type=""hidden"" name=""cmd"" value=""_s-xclick"">");
strForm.Append(#"<input type=""hidden"" name=""hosted_button_id"" value=""10956105"">");
strForm.Append(#"<input type=""hidden"" name=""on0"" value=""Venue"">");
strForm.Append(#"<input type=""text"" name=""os0"" value=""{0}"" maxlength=""60"">");
strForm.Append("</form>");
return String.Format(strForm.ToString(), venue);
}
getPayPalPostJS
private String getPayPalPostJS(string strFormId)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var paypalForm = document.forms.namedItem('{0}');");
strScript.Append("paypalForm.submit();");
strScript.Append("</script>");
return String.Format(strScript.ToString(), strFormId);
}
However, if i select the radio button, and a venue, and press the button, nothing happens....
Any ideas where i've gone wrong?
I followed this guide: http://www.netomatix.com/development/postrequestform.aspx
Here's a much cleaner, server-side solution to the ASP.NET/PayPal single form problem:
http://codersbarn.com/post/2008/03/08/Solution-to-ASPNET-Form-PayPal-Problem.aspx
The root of the problem is that ASP.Net web forms wrap everything on the page inside of one large <form> tag. Your paypal code is rendering a nested form and that doesn't work.
Read this question for more information.