I have two submit buttons in one form. I want to call different actions in both buttons. Is there any way to accomplish this without using JavaScript.
Calling different actions is not possible without javascript. You could call the same controller action and inside this action determine which button was pressed using the name property:
<% using (Html.BeginForm()) { %>
<input type="submit" name="save" value="Save" />
<input type="submit" name="update" value="Update" />
<% } %>
and in your controller action:
[HttpPost]
public ActionResult Index(string save)
{
if (!string.IsNullOrEmpty(save))
{
// the save button was pressed
}
else
{
// the update button was pressed
}
return View();
}
Give the buttons different name attributes. Then in your view handler (or equivalent - sorry, not an ASP.NET MVC person), you can check if that button's name is in the HTTP response and act accordingly.
Only one of the submit button names should exist in the response.
Of course there is!
for example, we have following form:
<form>
<input name='customer_name' type='text'/>
<input name='update_user' type='submit' value='Update user info'/>
<input name='delete_user' type='submit' value='Delete user'/>
</form>
when server gets form request there exists only one parameter in the collection: either update_user or delete_user. depends on what user has pressed.
Related
In Asp.net MVC, Is it possible to have a form post to two different actions based on model value when clicked on the same button?
Ex. - I want to add a new customer or update an existing customer on click of the same button "Save". Can the form be posted to two different action methods based on the customer's id value.
if the customer id value = 0 , then post it to "Create" acction method , if the customer id value is already present (not equal to 0), then post the form to "Update" action method?
Is this possible in asp.net mvc?
No You cant call multiple action on submit with fairly way,
You need to add hiddenfield for id
<input type="hidden" name="id" value="#model.Id" />
When you submit the form the value will be retrieve from model
And check the hidden field value is 0 or not
If 0 than the entity needs to create else it is for update
public ActionResult Save(Customer customer){
if(customer.id > 0){
// Update Entity
}
else{
// Create Entity
}
}
Yes. It is possible. There are multiple ways to do it.
1) You can conditionally set the form action attribute value based on your view model property value.
<form method="post" action="#(Model.Id==0?Url.Action("Create","Home")
:Url.Action("Update","Home"))">
<input type="text" name="FirstName" />
<button type="submit">Save</button>
</form>
2) Another option is, you can add html5 formaction to your submit button and the value of that attribute could be the url to create or update action method based on your Id property value.
#using (Html.BeginForm("Create", "Home"))
{
<input type="text" name="FirstName" />
<button type="submit"
formaction="#(Model.Id==0?Url.Action("Create","Home")
:Url.Action("Update","Home"))">Save</button>
}
When you specify the formaction attribute on a submit button, it will overrides the parent form's action attribute value.
3) Another option is to hijack the form submit event in javascript, prevent the default behavior (stopping the form submit) and then update the form's action attribute value to /create or /update and trigger form submit using javascript. You can keep the Id property value in a hidden field inside the form and read the value of that and use that to determine what should be the url for the form's action attribute value.
Assuming you have a hidden element for the Id of type int property in your page
#model YourViewModel
#using (Html.BeginForm("Create", "Home",FormMethod.Post,new {id="yourFormId"}))
{
#Html.TextBoxFor(a=>a.FirstName)
<button type="submit">Save</button>
#Html.HiddenFor(a=>a.Id)
}
and the javascript to hijack the form submit and update the form's action attribute value would be like
$(function () {
$("#yourFormId").submit(function(e) {
e.preventDefault(); // stop the normal form submit
var id=parseInt($("#Id").val());
var url=$(this).attr("action");
if(id===0)
{
url='/Home/Update'; // Use the Url.Action to be safe to generate this
}
// read the data attribute and update the forms action and do a submit
$(this).closest("form").attr('action', url).submit();
});
});
4) Another option is always submitting the form to Update or Create action and inside that method, based on the the Id property value, execute the code for Update or Create as needed.
Yes. This for the View case:
#mode MyModel
#{
string action = Model.Id == 0 ? "Create" : "Edit"
}
#using (Html.BeginForm(action, "MyController"))
{
// if Edit need Id
if(action == "Edit")
{
#Html.HiddenFor(model=> model.Id)
}
#Html.TextBoxFor(model >= model.Name);
<input type="submit" value="Save">
}
Let's suppose I have a form with two submit buttons: save and delete.
How can I remove/disable model validations on delete button?
Assuming you're using standard unobtrusive/jQuery validate; Disable client-side validation by putting a class of "cancel" on the button:
<button type="submit" class="cancel">Delete</button>
This will prevent client-side validation from firing at all in the event of this button being clicked.
For server side, just don't check if the model's valid or not.
For example, if you have a property Name on the model and you want NOT to validate it on delete.
You first need to differentiate if the httppost is coming from the save or delete button.
Add to your Model field IsDelete.
I suggest you add in your view something like:
#Html.HiddenFor(x => x.IsDelete)
Add onclick event to your delete button:
<button type="submit" onclick="javacript: $('#IsDelete').val('true');"> Delete </button>
In the controller do something like:
public ActionResult MyAction(MyModel model)
{
if(model.IsDelete)
ModelState.Remove("Name");
var valid = ModelState.IsValid();
}
You can use two separate forms in the view for the edit and delete.
Ex:
#using(Html.BeginForm("Edit", "Employee"))
{
//Edit inputs - ex textboxes for employee details such as name, age...
<input type="submit" value="Edit" />
}
#using(Html.BeginForm("Delete", "Employee"))
{
//Delete inputs - ex: hidden input for employee id
<input type="submit" value="Delete" />
}
Posting a form from .cshtml. If the Email Textbox has the value of "Admin" and the Password TextBox has the value of "12345" I want to include an onclick event on the submit button.
I thought about if/else block but what to place in the if condition below where you see question mark (?):
<form class="fvalidate" action="/entry" method="post">
<input type="text" name="Email" class="email required"/>
<input type="password" name="Sifre" class="required" />
#if (?)
{
<input type="submit" value="LOG IN" class="mTop15"
onclick="ibFunc.openBoxOpen('/entry/adv'); return false;" />
}
else
{
<input type="submit" value="LOG IN" class="mTop15" />
}
</form>
How could I accomplish this?
You need to understand the flow of the application and what fires when. You seem to be mixing Client and Server side technology.
The flow should be
Step 1 Submit the form
Step 2 The controller validates the login and works out whether they are admin or not.
Step 3 The controller redirects the user to the /entry or /entry/adv page depending on whether they are an admin or not
Step 4 On the /entry page don't fire the javascript
Step 4a On the /entry/adv page fire the javascript
To answer your question directly. There is nothing you can put in the place of the ? that will do what you want because that is Razor code which is executed on the server before the user has interacted with the page.
Do the control in POST in the controller, when the "Admin" submit the form make an if then use
return RedirectToAction("adv", "entry");
I have two submit buttons which call the same action method. How can I tell which of these buttons was clicked in the formcollection of the action method (without setting the value property of the buttons)?
HTML code for buttons:
<input type="submit" name="button" />
<input type="submit" name="button" />
Action method as:
public ActionResult submitted(FormCollection form)
{
}
i know how to do if we have a value property, but I just want to try like this without value property. How can this be done?
thanks,
michaeld
The best thing to do, is intercept the click action to set a hidden form variable before the form is submitted, e.g.:
<script language="text/javascript">
$("form input[submit]").click(function() {
$("#buttonSelected").val("some unique value here");
});
</script>
Where you might have a hidden input:
<input type="hidden" id="buttonSelected" name="buttonSelected" />
That way, you can then check the specific "buttonSelected" form value to figure out which button was pressed.
I have a View in which the user is able to upload a file to the server.
In this view I also have 2 buttons: one to Upload a file and other to Download the last file imported.
In my Controller I created 2 action methods: Import and Export.
How could I manage to redirect each button click to the proper action method in my Controller?
I have tried Html.ActionLink:
<%= Html.ActionLink("Upload", "Import", "OracleFile")%>
<%= Html.ActionLink("Download", "Export", "OracleFile")%>
Html.ActionLink didn't do the trick. The action links were taking me to the right Action methods but they were generating a GET request. This way Request.Files.Count = 0.
I need a POST request.
Note: the most intriguing part is that the upload was working and all of sudden it stopped working. I've seen that some people are having the same problem with FileUpload tasks in which the Request.Files is always Empty. I think it's empty because you need a post to the server. Isn't it?
maybe this will give u the idea:
view:
<form enctype="multipart/form-data" method="post" action="/Media/Upload/Photo">
<input type="file" name="file" id="file" />
<input type="submit" name= "submitImport" value="Upload" />
<input type="submit" name = "submitExport" value="Download" />
</form>
controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Action (FormCollection formCollection)
{
if (formCollection["submitImport"] != null)
{
return Import(formCollection);
}
if (formCollection["submitExport"] != null)
{
return Export(formCollection);
}
}
the Export and Import are the appropriateactions
You have to use a "multipart/form-data" form, and submit the form. No ActionLink.
<form enctype="multipart/form-data" method="post" action="/Media/Upload/Photo">
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" />
</form>
To generate a POST request for the upload, use the File Input form element and just post back to the server ala normal.
http://www.w3schools.com/jsref/dom_obj_fileupload.asp
Have a look at this blog post from Scott Hanselman.
http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx