How to handle a send parameter button in asp.net MVC c #?
<form id="form" name="form" action="" method="post">
<label>Nom : </label>
<input type="text" id="NAME" name="NAME" class="form-control" value=#Model.NAME required />
<input type="submit" value="importer />
</form>
Use Ajax begin Form to get it
In the Html
#using (Ajax.BeginForm("test", "Inicio", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Sucesso(data);" }))
{
<label>Nom : </label>
<input type="text" id="name" name="name" class="form-control" required />
<input type="submit" value="importer" />
}
In The controller
[HttpPost]
public ActionResult test(string name)
{
return Json(new { retorno = name }, JsonRequestBehavior.AllowGet);
}
Related
I have a basic form for which I want to handle buttons inside the form by calling the ActionResult method in the View's associated Controller class. Here is the following HTML5 code for the form:
<h2>Welcome</h2>
<div>
<h3>Login</h3>
<form method="post" action= <!-- what goes here --> >
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
</form>
</div>
<!-- more code ... -->
The corresponding Controller code is the following:
[HttpPost]
public ActionResult MyAction(string input, FormCollection collection)
{
switch (input)
{
case "Login":
// do some stuff...
break;
case "Create Account"
// do some other stuff...
break;
}
return View();
}
you make the use of the HTML Helper and have
#using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="#Url.Action("MyAction", "MyController")" >
Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
#using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>#Model.Title</strong> will be deleted.</p>
#using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
#Url.ActionLink("go to list", "Index")
}
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/ActionMethod?userName=#Model.UserName">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
How to pass some value from the form to the controller using the FormCollection method. But the controller return null.And the form is located inside a modal popup window..
View
<form action="/Home/AddToCart" method="post">
<input type="hidden" id="vid" name="vid" class="hiddenid" />
<div class="styled-input agile-styled-input-top">
<input type="text" placeholder="Name" name="name" id="name" required>
</div>
<div class="styled-input">
<input type="text" placeholder="Star Name" name="star" id="star" required>
</div>
<input type="submit" value="Add To Cart">
</form>
Controller
[HttpPost]
public ActionResult AddToCart(FormCollection data) {
var cart = new cart {
vid = Convert.ToInt32(data["vid"]),
name = data["name"],
star = data["star"]
};
userService.AddToCart(cart);
ViewBag.p = userService;
return RedirectToAction("Temple");
}
I am trying to implement worldpay payment method in my MVC project and trying to make a test payment but it shows me this error
You have completed or cancelled your payment.
You have cookies disabled. To complete your payment, enable
cookies by changing the privacy settings in your browser. Then
return to the merchant's site and resubmit your payment.
Your session at WorldPay has timed out. Please return to the
merchant's site and resubmit your payment.
Code that i am trying
<form action="https://secure-test.worldpay.com/wcc/purchase" method="post">
<input name="address1" type="hidden" value="10 Downing Street" />
<input name="amount" type="hidden" value="100.00" />
<input name="cartId" type="hidden" value="DAW" />
<input name="op-DPChoose-VISA^SSL" type="hidden" value="DAW" />
<input name="cardNoInput" type="hidden" value="4444333322221111" />
<input name="country" type="hidden" value="GB" />
<input name="currency" type="hidden" value="GBP" />
<input name="email" type="hidden" value="dave#gov.uk" />
<input name="instId" type="hidden" value="eca6aba9-16b2-4ad0-8019-1212bbb2f152" />
<input name="name" type="hidden" value="Prime Minister" />
<input name="postcode" type="hidden" value="SW1A 2AA" />
<input name="tel" type="hidden" value="020 7925 0918" />
<input name="testMode" type="hidden" value="100" />
<input name="town" type="hidden" value="London" />
<input name="cardCVV" type="hidden" value="1234" />
<input name="cardExp.month" type="hidden" value="1" />
<input name="cardExp.year" type="hidden" value="2017" />
<div class="form-group">
<button class="btn btn-success btn-lg" type="submit">WorldPay Test Checkout</button>
</div>
</form>
Try this for test Order placement through WorldPay
<form action="/complete" id="paymentForm" method="post">
<span id="paymentErrors"></span>
<div class="form-row">
<label>Name on Card</label>
<input data-worldpay="name" name="name" type="text" />
</div>
<div class="form-row">
<label>Card Number</label>
<input data-worldpay="number" size="20" type="text" />
</div>
<div class="form-row">
<label>CVC</label>
<input data-worldpay="cvc" size="4" type="text" />
</div>
<div class="form-row">
<label>Expiration (MM/YYYY)</label>
<input data-worldpay="exp-month" size="2" type="text" />
<label> / </label>
<input data-worldpay="exp-year" size="4" type="text" />
</div>
<input type="submit" value="Place Order" />
</form>
Then add this script in your view file
<script src="https://cdn.worldpay.com/v1/worldpay.js"></script>
<script type="text/javascript">
var form = document.getElementById('paymentForm');
Worldpay.useOwnForm({
'clientKey': 'Your_Client_Key',
'form': form,
'reusable': false,
'callback': function (status, response) {
document.getElementById('paymentErrors').innerHTML = '';
if (response.error) {
Worldpay.handleError(form, document.getElementById('paymentErrors'), response.error);
} else {
var token = response.token;
Worldpay.formBuilder(form, 'input', 'hidden', 'token', token);
console.log(token);
$.ajax({
url: "/Home/payment/",
data: { token: token },
success: function (data) {
},
dataType: "html",
type: "POST",
cache: false,
error: function () {
//Error Message
}
});
form.submit();
}
}
});
</script>
Now add this Order Placement code in your controller
public ActionResult payment(string token)
{
var restClient = new WorldpayRestClient("https://api.worldpay.com/v1", "Your_Service_Key");
var orderRequest = new OrderRequest()
{
token = token,
amount = 500,
currencyCode = CurrencyCode.GBP.ToString(),
name = "test name",
orderDescription = "Order description",
customerOrderCode = "Order code"
};
var address = new Address()
{
address1 = "123 House Road",
address2 = "A village",
city = "London",
countryCode = CountryCode.GB,
postalCode = "EC1 1AA"
};
orderRequest.billingAddress = address;
try
{
OrderResponse orderResponse = restClient.GetOrderService().Create(orderRequest);
Console.WriteLine("Order code: " + orderResponse.orderCode);
}
catch (WorldpayException e)
{
Console.WriteLine("Error code:" + e.apiError.customCode);
Console.WriteLine("Error description: " + e.apiError.description);
Console.WriteLine("Error message: " + e.apiError.message);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
i have a form in html and i want to submit it to a controler
what i have tried
#using (Html.BeginForm("RegisterApartmentOwner", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<p>
<label>First Name</label>
<input type="text" placeholder="Enter your first Name" name="firstName" />
<span class="errorMessage"></span>
</p>
<p>
<label>Last Name</label>
<input type="text" placeholder="Enter your last Name" />
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="text" placeholder="Enter your password" name="Password"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password Again</label>
<input type="text" placeholder="Enter your password again" name="Password2"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Mobile Number</label>
<input type="text" placeholder="Enter your mobile number" />
<span class="errorMessage"></span>
</p>
<p>
<input type="submit" value="Register" class="submit"/>
</p>
}
</div>
and in the controller i receive the submit in this function
public String RegisterTenant() {
return "done";
}
i can see the done message, however, i want to receive the values of the input that i used in the form, how please?
i just to know what to receive the form in the controller
You could accept the formcollection (as in: FormCollection collection) as a parameter in your post action, or, better yet, create a view model, send that to the view and post it to the controller. You'd have to set it as a parameter of your http post action course.
Example:
[HttpPost]
public String RegisterTenant(FormCollection collection) {
// give all your html elements you want to read values out of an Id, like 'Password'
var password = collection["Password"];
// do something with your data
return "done";
}
Or (better!):
View model:
public class HomeViewModel
{
[Required]
public string UserName {get;set;}
}
View (on top):
#model Namespace.HomeViewModel
View (in your form):
#Html.TextBoxFor(m => m.UserName)
Controller:
[HttpPost]
public String RegisterTenant(HomeViewModel model)
{
var userName = model.UserName;
// do something
}
But you should really do some investigation into MVC: Views, Models & Controllers and what they do. It is really better to create a typesafe view model and work with that.
When I use the bootstrap search form like this, I get this output (as I wanted):
#using (Html.BeginForm("Search", "Show", FormMethod.Get, new { #class = "form-search" })) {
<div class="input-append">
<input type="search" class="span2 search-query" name="query" />
<input type="submit" class="btn" value="Search" />
</div>
}
However, when I want to turn this into a ajax form, I'm receiving this output:
#using (Ajax.BeginForm(
new AjaxOptions {
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "contentlist"
})) {
<div class="input-append">
<input type="search" class="span2 search-query" name="query" />
<input type="submit" class="btn" value="Search" />
</div>
}
Why does the type of form make a difference? The generated HTML is the same in both cases.
Edit: solved, I'm a dumbass.
I think there is no class name for the ajax form. You should add class = "form-search".