Calling C# function By action [duplicate] - c#

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!

Related

Post Form Value on Submit Click from Entity Framework Identity Scaffolded Razor Page

In my .cshtml file I have a form which works fine for my MVC pages:
<form action="#Url.Action("SaveUserEntryAsync", "ConfirmEmail")" method="post">
<label class="modal-body1 col-form-label" id="confirmEmailPageComingSoonModalFormLabel">Modal Error!3</label>
<br />
<textarea class="form-control" name="newsfeedUserEntry" id="newsfeedUserEntry" type="text"></textarea>
<div class="modal-footer">
<button type="submit" id="ComingSoonModalFooterSubmitButton" class="btn btn-success" data-dismiss="confirmEmailPageComingSoonModal">#_loc[Model.Submit]</button>
</div>
</form>
In my scaffolded cshtml.cs file I have a public async Task<IActionResult> SaveUserEntryAsync(string newsfeedUserEntry) method.
<form action="#Url.Action("SaveUserEntryAsync", "ConfirmEmail")" method="post"> does not work with the Razor page and I cannot find the correct syntax so that my button works on the page. Any help would be appreciated?
First of all, change #Url.Action instead of you have to use #Url.Page or use asp-page directly like #Rena says. and change your code:-
<button type="submit" id="ComingSoonModalFooterSubmitButton" class="btn btn-success" data-dismiss="confirmEmailPageComingSoonModal">aaa</button>
to
<input type="submit" id="ComingSoonModalFooterSubmitButton" data-dismiss="confirmEmailPageComingSoonModal" value=#_loc[Model.Submit] class="btn btn-success/>
Hope it will resolve your issue.
For Razor Pages, it uses razor pages and page handler. #Url.Action() targets to MVC controller and action. You could use #Url.Page(string pageName, string pageHandler). Asume you have a ConfirmEmail.cshtml and ConfirmEmail.cshtml.cs:
<form method="post" action="#Url.Page("ConfirmEmail", "SaveUserEntry")" >
#Html.AntiForgeryToken()
<label class="modal-body1 col-form-label" id="confirmEmailPageComingSoonModalFormLabel">Modal Error!3</label>
<br />
<textarea class="form-control" name="newsfeedUserEntry" id="newsfeedUserEntry" type="text"></textarea>
<div class="modal-footer">
<button type="submit" id="ComingSoonModalFooterSubmitButton" class="btn btn-success" data-dismiss="confirmEmailPageComingSoonModal">aaa</button>
</div>
</form>
Or you could use asp-page and asp-page-handler like below:
<form asp-page="ConfirmEmail" asp-page-handler="SaveUserEntry" method="post">
<label class="modal-body1 col-form-label" id="confirmEmailPageComingSoonModalFormLabel">Modal Error!3</label>
<br />
<textarea class="form-control" name="newsfeedUserEntry" id="newsfeedUserEntry" type="text"></textarea>
<div class="modal-footer">
<button type="submit" id="ComingSoonModalFooterSubmitButton" class="btn btn-success" data-dismiss="confirmEmailPageComingSoonModal">aaa</button>
</div>
</form>
Note: No need to add Async suffix in request url.
For the handler, it shoud be OnPostXXX(XXX should be the handler name):
public class ConfirmEmailModel : PageModel
{
public void OnGet()
{
}
public async Task<IActionResult> OnPostSaveUserEntryAsync(string newsfeedUserEntry)
{
return Page();
}
}
Reference:
https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-5.0&tabs=visual-studio#multiple-handlers-per-page

How to handle a send parameter button in asp.net MVC c #?

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);
}

Why this Action Method is not receiving any value from the form?

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");
}

POST data to controller with ASP.NET MVC

I am using ASP.NET MVC with C# and pure bootstrap. One of my views contains a label, text input box, and a submit button:
#{
ViewBag.Title = "BinSearch";
Layout = "~/Views/Shared/_LayoutSearch.cshtml";
}
<h2>BinConfig Search</h2>
#using (Html.BeginForm("FiEdit", "EditConfigController"))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}
When I click the "submit" button, I would like to transfer the data to a controller, EditConfigController to this method:
[HttpPost]
public ActionResult FiEdit(int key)
{
return View(new IssuerKey().Key = key);
}
Which then is supposed to create a new view where I can edit data based off the key provided. This is the FiEdit view:
#model BinFiClient.Models.IssuerKey
#{
ViewBag.Title = "FiEdit";
Layout = "~/Views/Shared/_LayoutEdit.cshtml";
}
<h2>FiEdit</h2>
However, when I click the "submit" button, I receive a 404 error, and the URL path looks like this:
http://localhost:58725/EditConfigController/FiEdit
Which is actually the path to the method in the controller that I posted above.
What I need is basically a way to POST data to another controller. How can I accomplish this?
Edit:
Now I am receiving the error:
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'BinFiClient.Models.IssuerKey'.
Try replacing your code with the following:
#using (Html.BeginForm("FiEdit", "EditConfig", FormMethod.Post))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}
This will POST the parameter key to the EditConfig controller.
If you'd like to post to the action TestEdit in another controller, say the TestController, your code should be changed to the following:
#using (Html.BeginForm("TestEdit", "Test", FormMethod.Post))
...
To resolve the "model item passed into the dictionary" error, change your POST to be this:
[HttpPost]
public ActionResult FiEdit(int key)
{
return View(new IssuerKey() { Key = key });
}
ou can try with:
#using (Html.BeginForm(("FiEdit", "EditConfigController", FormMethod.Post,
new { enctype = "multipart/form-data" })))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}

mvc4 receive form in a controller

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.

Categories

Resources