I want to call my method in my mvc view. I have a method called SavePersoon wich has to save the changed data into my database. This is my code from my services:
public bool SavePersoon(PersoonModel persoon)
{
bool result = true;
db.Persoon.AddOrUpdate(persoon.GetPoco());
db.SaveChanges();
return result;
}
This is the button who has to be pressed and then this code above has to deal the work itself.
The view:
<button type="button" id="btnSaveChanges" class="btn btn-primary">Opslaan</button>
Do I have to use something similair like <asp:LinkButton...?
You can make use of Ajax , Something like this
$("#btnSaveChanges").on("click",function(){
$.ajax({
url:"/controllerName/SavePersoon",
data:$("#formName").serialize(),
cache:false,
type:"POST",
error:function(){
alert("Error");
}
});
});
If you use Razor view engaine, you can make your method return an action result and call it from the view using Html.Actionlink.
You can do 2 things:
Use the HTML Helpers that ASP.Net MVC provides to create a form which posts to the required method, something like 'Save' of the controller 'Person':
#using (Html.BeginForm("Save", "Person", FormMethod.Post, new { #class = "form-horizontal" })) {
<div>
<!-- Your HTML, this could for example be a text field for the person its name -->
#Html.TextBoxFor(Model => Model.Name, new { #class = "form-control" })
<input type="submit" class="btn btn-primary" value="Save" />
</div>
}
This will create a form tag for you, something like <form action="person/save" method="post"> ... your HTML & the submit button ... </form>
An alternative is to use Ajax to prevent the page from refreshing as stated in the above post.
$("#btnSaveChanges").on("click",function(){
$.ajax({
url: '#Url.Action("Save", "Person")', // Again an MVC HTML Helper to create a URL
data:$("#Name").val(), // Posts the value of a text field with ID "Name"
cache:false,
type:"POST",
success: funcion(returnValue) {
// Do something with the result.
}
error:function(){
alert("Error");
}
});
});
I want to generate table with, for example, 4 columns. In last column i need link to remove user whitch is in that row. When i am using form tag like this:
#foreach (var item in Model.Approvers)
{
<tr>
<td>#item.FullName</td>
<td>#item.Email</td>
<td>#item.AdAccount</td>
<td>
<form id="removeApproverRoleForm" action="~/Admin/RemoveRole" method="post">
#Html.AntiForgeryToken()
<input type="text" id="userId" name="userId" value="#item.Id" />
<input type="text" id="role" name="role" value="Approver" />
Remove
</form>
</td>
</tr>
}
It passes last value of userId and role to RemoveRole method. It have to be POST method so this whould not work:
#Html.ActionLink(Remove, "RemoveRole", "Admin", new { role = "Approver", userid = item.Id }, new { onclick = "return removeRole();" })
Even if i place form tag above that, the parameters are still visible in the link.
So i need somehow use new { role = "Approver", userid = item.Id } but send it as a POST and hide those values.
Any ideas?
Thank you for help!
It is a popular problem, so you can find detailed solution here
Short answer is:
use <input type="submit">Remove</input> inside the form
OR use
#Ajax.ActionLink("Remove, "RemoveRole", "Admin", new { role = "Approver", userid = item.Id }, new AjaxOptions { HttpMethod = "POST" })
to be able to create ActionLink with controlling the method parameter.
I have a Ajax.BeginForm in my razor view. I want to have 3 check boxes.
Begineer
Intemidiate
advance
checkoxes can select for any combination. When I clicked submit button bellow method in my controller will triggered.
public PartialViewResult SearchCourseCriteria(){
var courses = from s in db.CourseCategories
select s;
return PartialView("_Courses", courses);
}
This is my view
#using (Ajax.BeginForm("SearchCourseCriteria", new AjaxOptions
{
UpdateTargetId = "CourseList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
}))
{
td>
#Html.CheckBoxFor()
</td>
<td>
<input type="submit" value="Search" class="btn " />
</td>
}
In my model there is field called CourseLevel. I want to know How to filter courses according to the selected checkboxes.
EX : If I select begineer and Intermidiate checkboex. I want to get all courseCategories from that levels. I dont know how to get that result. Help please.
In you view, generate 3 checkboxes for each value
<label>
<input type="checkbox" name="courselevel" value="Begineer" /> // Beginner?
<span>Begineer</span>
<label>
<label>
<input type="checkbox" name="courselevel" value="Intemidiate" /> // Intermediate?
<span>Intemidiate</span>
<label>
... // ditto for advance
Then add a parameter to the method
public PartialViewResult SearchCourseCriteria(string[] CourseLevel)
The value of CourseLevel will be an array of the selected checkboxes, for example [ "Begineer", "advance" ] if you checked the first and third checkboxes
You can then modify you query to
var courses = from s in db.CourseCategories
where CourseLevel.Contains(s.CourseLevel)
select s;
or
var courses= db.CourseCategories.Where(c => CourseLevel.Contains(c.CourseLevel));
Side note: I would recommend you use an enum to define the values for CourseLevel
I'm using MVC3. I learned that its a bad practice to delete an item using HttpGet Method as any one can browse to the url and deletes an item. So I want to perform delete operation on HttpPost Method.
The problem is that when I click delete button, it gets hit on HttpGet method only but not on HttpPost method.
I've used webgrid and its the index.cshtml file
<div id="DataTable">
#grid.GetHtml(htmlAttributes: new {id="gvMovies" },
columns:grid.Columns(
grid.Column("Title","Movie Title",canSort:true),
grid.Column("Director","Film Maker",canSort:false),
grid.Column(header:"Action",
format:#<text>
Edit
#using (Html.BeginForm("Delete", "Movies", new { id = #item.id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ActionLink("Delete", "Delete", new { id = #item.id }, new { onclick = "return confirm('Are you sure you wish to delete this article?');" })
}
</text>)))
</div>
The controller page is as follows
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id)
{
return RedirectToAction("Index");
}
Conceptually it's not correct to use the POST verb for delete. POST - is intended for posting information. The correct way would be to to just remove the attribute from the Delete method, and let it go with the GET verb.
Now if you really really really need to use the POST, your first mistake is that you create a link, instead of a submit button that will submit the form. Replace
#Html.ActionLink("Delete", "De...
with:
<input type="submit" value="Delete">
you must add submit button instead of link so you must change
#Html.ActionLink("Delete" to <input type=submit value="del" >
if you want send id in the post you can add hidden input in the form so you can add some thing like this before your submit button in the form
<input type="hidden" value=#item.Id name="itemid" >
so i think this code will work
#using (Html.BeginForm("Delete", "Movies", new { id = #item.id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="hidden" value=#item.Id name="itemid" >
<input type=submit value="del" >
}
A Razor view has 3 buttons inside a form. All button's actions will need form values which are basically values coming input fields.
Every time I click any of buttons it redirected me to default action. Can you please guide how I can submit form to different actions based on button press ?
I really appreciate your time, guidance and help.
You could also try this:
<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />
Then in your default function you call the functions you want:
if( Request.Form["submitbutton1"] != null)
{
// Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
// code for function 2
}
This elegant solution works for number of submit buttons:
#Html.Begin()
{
// Html code here
<input type="submit" name="command" value="submit1" />
<input type="submit" name="command" value="submit2" />
}
And in your controllers' action method accept it as a parameter.
public ActionResult Create(Employee model, string command)
{
if(command.Equals("submit1"))
{
// Call action here...
}
else
{
// Call another action here...
}
}
in the view
<form action="/Controller_name/action" method="Post>
<input type="submit" name="btn1" value="Ok" />
<input type="submit" name="btn1" value="cancel" />
<input type="submit" name="btn1" value="Save" />
</form>
in the action
string str =Request.Params["btn1"];
if(str=="ok"){
}
if(str=="cancel"){
}
if(str=="save"){
}
You can use JS + Ajax.
For example, if you have any button you can say it what it must do on click event.
Here the code:
<input id="btnFilterData" type="button" value="myBtn">
Here your button in html:
in the script section, you need to use this code (This section should be at the end of the document):
<script type="text/javascript">
$('#btnFilterData').click(function () {
myFunc();
});
</script>
And finally, you need to add ajax function (In another script section, which should be placed at the begining of the document):
function myFunc() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/myController/myFuncOnController",
data: {
//params, which you can pass to yu func
},
success: function(result) {
error: function (errorData) {
}
});
};
This is what worked for me.
formaction="#Url.Action("Edit")"
Snippet :
<input type="submit" formaction="#Url.Action("Edit")" formmethod="post" value="Save" class="btn btn-primary" />
<input type="submit" formaction="#Url.Action("PartialEdit")" formmethod="post" value="Select Type" class="btn btn-primary" />
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit( Quote quote)
{
//code
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PartialEdit(Quote quote)
{
//code
}
Might help some one who wants to have 2 different action methods instead of one method using selectors or using client scripts .
The cleanest solution I've found is as follows:
This example is to perform two very different actions; the basic premise is to use the value to pass data to the action.
In your view:
#using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
if (isOnDli)
{
<button name="removeDli" value="#result.WeNo">Remove From DLI</button>
}
else
{
<button name="performDli" value="#result.WeNo">Perform DLI</button>
}
}
Then in your action:
public ActionResult DliAction(string removeDli, string performDli)
{
if (string.IsNullOrEmpty(performDli))
{
...
}
else if (string.IsNullOrEmpty(removeDli))
{
...
}
return View();
}
This code should be easy to alter in order to achieve variations along the theme, e.g. change the button's name to be the same, then you only need one parameter on the action etc, as can be seen below:
In your view:
#using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
<button name="weNo" value="#result.WeNo">Process This WeNo</button>
<button name="weNo" value="#result.WeNo">Process A Different WeNo This Item</button>
}
Then in your action:
public ActionResult DliAction(string weNo)
{
// Process the weNo...
return View();
}
Try wrapping each button in it's own form in your view.
#using (Html.BeginForm("Action1", "Controller"))
{
<input type="submit" value="Button 1" />
}
#using (Html.BeginForm("Action2", "Controller"))
{
<input type="submit" value="Button 2" />
}
You could use normal buttons(non submit). Use javascript to rewrite (at an 'onclick' event) the form's 'action' attribute to something you want and then submit it. Generate the button using a custom helper(create a file "Helper.cshtml" inside the App_Code folder, at the root of your project) .
#helper SubmitButton(string text, string controller,string action)
{
var uh = new System.Web.Mvc.UrlHelper(Context.Request.RequestContext);
string url = #uh.Action(action, controller, null);
<input type=button onclick="(
function(e)
{
$(e).parent().attr('action', '#url'); //rewrite action url
//create a submit button to be clicked and removed, so that onsubmit is triggered
var form = document.getElementById($(e).parent().attr('id'));
var button = form.ownerDocument.createElement('input');
button.style.display = 'none';
button.type = 'submit';
form.appendChild(button).click();
form.removeChild(button);
}
)(this)" value="#text"/>
}
And then use it as:
#Helpers.SubmitButton("Text for 1st button","ControllerForButton1","ActionForButton1")
#Helpers.SubmitButton("Text for 2nd button","ControllerForButton2","ActionForButton2")
...
Inside your form.
Simplest way is to use the html5 FormAction and FormMethod
<input type="submit"
formaction="Save"
formmethod="post"
value="Save" />
<input type="submit"
formaction="SaveForLatter"
formmethod="post"
value="Save For Latter" />
<input type="submit"
formaction="SaveAndPublish"
formmethod="post"
value="Save And Publish" />
[HttpPost]
public ActionResult Save(CustomerViewModel model) {...}
[HttpPost]
public ActionResult SaveForLatter(CustomerViewModel model){...}
[HttpPost]
public ActionResult SaveAndPublish(CustomerViewModel model){...}
There are many other ways which we can use, see this article ASP.Net MVC multiple submit button use in different ways
As well as #Pablo's answer, for newer versions you can also use the asp-page-handler tag helper.
In the page:
<button asp-page-handler="Action1" type="submit">Action 1</button>
<button asp-page-handler="Action2" type="submit">Action 2</button>
then in the controller:
public async Task OnPostAction1Async() {...}
public async Task OnPostAction2Async() {...}
Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):
On HTML:
<form action="" method="post" role="form">
<table>
#for (var i = 0; i < Model.List.Count(); i++)
{
<tr>
<td>#Model.List[i].ItemDescription</td>
<td>
<input type="submit" value="REMOVE" class="btn btn-xs btn-danger"
asp-controller="ControllerName" asp-action="delete" asp-route-idForDeleteItem="#Model.List[i].idForDeleteItem" />
</td>
</tr>
}
</table>
</form>
On Controller:
[HttpPost("[action]/{idForDeleteItem}"), ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(long idForDeleteItem)
{
///delete with param id goes here
}
Don't forget to use [Route("[controller]")] BEFORE the class declaration - on controller.
Information acquired from:
http://www.codedigest.com/posts/46/multiple-submit-button-in-a-single-form-in-aspnet-mvc
For you chaps coming more recently, you can use the HTML 5 Formaction Attribute.
In your <input> or <button>
Just define:
<button id="btnPatientSubmit" type="submit" class="btn btn-labeled btn-success" formaction="Edit" formmethod="post">
Notice the addition of formation= "Edit", this specifies which ActionResult I want to submit to in my controller.
This will allow you to have multiple submit buttons, where each could submit to independent ActionResults (Methods) in your controller.
This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
#{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
In case you're using pure razor, i.e. no MVC controller:
<button name="SubmitForm" value="Hello">Hello</button>
<button name="SubmitForm" value="World">World</button>
#if (IsPost)
{
<p>#Request.Form["SubmitForm"]</p>
}
Clicking each of the buttons should render out Hello and World.