multiple button click in asp.net MVC 3 - asp.net-mvc-3

I am having multiple dynamic buttons on my asp.net mvc 3 page. what is the best way to handle button click in asp.net mvc 3? there is no event handling in asp.net, so what is the best practice to hadle.?

You could handle the buttons clicks using javascript by subscribing to their click event. For example with jQuery you could give those buttons a class and then:
$(function() {
$('.someClass').click(function() {
// a button was clicked, this will point to the actual button
});
});
or if those are submit buttons of a form you could give them the same name and different values and then on the server test the value of the name parameter. It's value will equal to the button that was clicked.
Let's suppose for example that you have the following form with multiple submit buttons:
#using (Html.BeginForm())
{
... some input fields
<button type="submit" name="Button" value="delete">Delete data</button>
<button type="submit" name="Button" value="save">Save data</button>
}
Now inside the controller action you are posting to you could determine which button was clicked:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
var button = Request["button"];
if (button == "save")
{
// the save button was clicked
}
else if (button == "delete")
{
// the delete button was clicked
}
...
}

If the buttons do not require the same form data, then you can create two forms with different action methods. This is the easiest solution.
If you need to use the same form data, then there are a number of methods, inclduing Darin and tvanfosson's approaches. There is also an approach based on attributes that will select the correct action method based on which button is clicked.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=724

Depends on what the buttons are doing. If they are logically separate actions, then you could have each postback to a separate action on the server side. This often also works they are variants of the same action, Save vs. Cancel, for instance where Save posts back the form and Cancel redirects to you the previous url (say, going back to details from edit). If the buttons represent different data that would get posted back to the same action, you can give them different values. If the buttons are named, the values will get posted back along with the rest of the form, assuming they are included in the form. If posting back from AJAX, you might need to explicitly serialize the button value along with the form.
Example of Save/Cancel
#using (Html.BeginForm())
{
//...
<button type="submit" class="submit-button button">Save</button>
#Html.ActionLink( "Cancel", "details", new { ID = Model.ID }, new { #class = "cancel-button button" } )
}
Then use CSS, perhaps in conjunction with jQuery UI to style the buttons.
<script type="text/javascript">
$(function() {
$('.button').button();
...
});
</script>

Related

MVC: Allow multiple click of the same button

Is it possible to allow multiple clicks on a sigle submit button of a form? I have a form where I want to perform an action on the first submission (first click) and a different action on the second submission (second click).
I am basically using ajax to populate a div in the form during the first submission and I want to submit the form on the second click.
I have tried to put by button in the div to by updated, and after the first click, I update update the div and re-creating the button in the updated div. But if I use this method, how can I set the action method of the newly created button in my controller method for Ajax?
My controller method returns something like
return Content( mystring + <input type='button' value='continue submission'/>
if i use this approach, how do I set the action method of the buttton, or is there another way of doing this?
Use two buttons with JavaScript:
Button 1 is shown initially. On click, it hides itself, shows button 2, and performs your action 1.
Button 2 is hidden initially. It is unhidden by button 1 and on click, it performs your second action.
This looks a little weird but I can tell you how to do this. Take an input type="submit" and make it hidden. Have a variable as var flag = false; When user first clicks you input type="button" call a function and do your stuff and make sure to make the flag=true; In the function itself check if flag=true; the trigger the event of your input type="submit".
Like as follows:
<input type="button" id="btn1" onclick="perfromAction()" value="submit"/>
<input type="submit" id="btn2" value="submit" style="display:none"/>
<script type="text/javascript">
var flag=false;
function performAction()
{
if(flag){
$("#btn2").trigger("click");
}
else{
//do processing
flag=true;
}

MVC3: Button action on the same view

i wish to change the inner html of a view on button click but maintain the view. I know how to change the html content of a div in javascript, but how can I have the action of the button not return a different view?
My buton looks like
<input type="submit" value="submit" onchange="myfunc()"/>
where myfunc() is the function in Javascript changing the div content.
Assuming you want a link to render content using ajax (and hopefully using razor) you can do something like the following:
First, setup the action to render the content partially. this can be done a few ways, but I'll keep with the logic in the action (and make it callable directly or by ajax):
[HttpPost]
public ActionResult Save(SomeModel model)
{
/* build view */
return Request.IsAjaxRequest() ? PartialView(model) : Wiew(model);
}
Next, setup a container in your page where the content will be populated along with the form you're looking to submit. If you want the form to disappear on a save, wrap it in the container. Otherwise, keep the container separated. In the below example, the from will submit and on success it'll come back, otherwise the new content will appear in its place:
<div id="ajaxContentPlaceholder">
#using (Ajax.BeginForm("Save", new AjaxOptions { UpdateTargetId = "ajaxContentPlaceholder" })) {
<!-- form elements -->
<input type="submit" value="save" />
}
</div>

Add and remove textbox at runtime in mvc3

In my page there is one textbox by default and one add button beside it. I need to add the another textbox when user click Add button. And there should be two buttons Add and Remove beside newly added text box. And same process goes on i.e., user can add Textbox using Add button and remove it using remove button.
I am new to mvc 3 so i am confused how to proceed. Is there any way like placeholder in asp.net so that we can add control at runtime.
Any suggestion and idea will be helpful to me
MVC is a very "hands-off" framework compared to Web Forms, so you're free to add the new textboxes how you like. Note that "controls" don't exist in MVC.
Here's how I'd do it:
Model:
class MyModel {
public Boolean AddNewTextBox { get; set; }
public List<String> MultipleTextBoxes { get; set; } // this stores the values of the textboxes.
}
View (I prefer the Web Forms view engine, I'm not a fan of Razor):
<% for(int i=0;i<Model.MultipleTextBoxes.Count;i++) { %>
<%= Html.TextBoxFor( m => m.MultipleTextBoxes[i] ) /* this might look like magic to you... */ %>
<% } %>
<button type="submit" name="AddNewTextbox" value="true">Add New Textbox</button>
<button type="submit">Submit form</button>
Controller:
[HttpPost]
public ActionResult MyAction(MyModel model) {
if( model.AddNewTextBox ) model.MultipleTextBoxes.Add("Yet another");
else if( ModelState.IsValid ) {
// your regular processing
}
}
You can also add more textboxes with Javascript and it work perfectly fine. All that matters is the HTML input elements. There's no cryptic viewstate. MVC is stateless.
Note that because I used <button type="submit"> my example will not work reliably in Internet Explorer 6-8 (sucks, I know), but you can replace them with <input type="submit"> with no ill-effects.
This requires some Javascript/JQuery... The following is a sketch only, but will hopefully be useful as a general approach.
The remove button
You want to render a button that can target its own container for removal. To do that, use some markup like this:
<div class="item-container">
<input type="button" onclick="removeItem(this)" />
</div>
And the Javascript for removeItem:
<script>
function removeItem(element) {
// get the parent element with class "item-container" and remove it from the DOM
$(element).find(".item-container").remove();
}
</script>
The add button
You could either use a partial view with Ajax, or use straight Javascript; which one is best likely depends on whether you need a round-trip to the server to create a new item. Let's say you need to go the the server to generate a new ID or something.
First, create a partial view and corresponding controller action; this should contain the remove button as above, as well as the text box and add button.
Now, create an Ajax form on your main page that gets invoked when you click Add:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("New", new AjaxOptions() { UpdateTargetId="ajaxTarget", HttpMethod = "GET" })) {
<input type='submit' value='Add New' />
}
<div id="ajaxTarget"></div>
This code fetches your partial view (from the action New in the current controller) and adds the result to the ajaxTarget element.
Note The Ajax form requires Unobtrusive Ajax, which you can install via Nuget: Install-Package JQuery.Ajax.Unobtrusive.

ASP.NET MVC - Having a confirmation button with a Form

I have an strongly typed view for my model and what I'd like is that when the user clicks on submit, a confirmation box pop up confirming that the user does indeed wish to submit the form, if they click cancel then it shouldn't fire the HttpPost Action for that View, is this possible?
Of course it is possible. I like to use an unobtrusive approach. Here is a simplified example:
jQuery(document).ready(function () {
jQuery('[data-confirm]').click(function (e) {
if (!confirm(jQuery(this).attr("data-confirm")))
{
e.preventDefault();
}
});
});
Then you only need to add a data-confirm attribute to your submit button for example
<input type="submit" data-confirm="are u sure?" />
Of course you can use this attribute on links, buttons, etc. you are not restricted to submit buttons only, and if you want to implement a fancier confirm dialog later than you will have to replace the code only in one place.
function doSubmit()
{
if(window.confirm("ARE YOU SURE TO PERFORM THIS ACTION"))
{
return true;
}
else return false;
}
call doSubmit() function on onsubmit event of the form,
Eg- onsubmit="return doSubmit()
you can add a simply jQuery call for that.
at the end of your view add:
<script type="text/javascript">
$("form").submit(function() {
return confirm('Are you sure?');
});
</script>
or, add a
onsubmit="return confirm('Are you sure?');"
as a new element property
I believe this can be done by overriding the submit button using jquery. Jquery .submit()
This way, when the person hits submit you can show a message and either submit it or cancel it.

Is it possible to load a partial view by selecting a Radio Button in mvc3

Can i use radio button's to select two different partial view, Without using Jquery?
yes and no. a partial can only be loaded (after initial page load) via ajax, so a partial page refresh isn't possible without using ajax. however, you could submit the selected radio button (via javascript) to the controller action and then determine inside the controller which radio button had been selected. It would then just be a case of selecting the appropriate view.
As I said, you can't go down the partial route without ajax in the mix, so the answer is no. also, you'd still have to use javascript in order to use the radio button in the submit, in which case, an ajax solution might be worth thinking about.
[edit] with deference to Splash-X, here's a quick work up of the hidden div scenario:
#*use either #Html.RenderPartial() or #Html.RenderAction() as required*#
<div id="developerDiv" style="display: none">
This is the developer stuff, in reality,
this would be populated as such #*#Html.RenderPartial("DeveloperPartial")*#
</div>
<div id="testerDiv" style="display: none">
And here we have the testers, again,
this would be populated as such #*#Html.RenderPartial("TestersPartial")*#
</div>
<div>
Developer :#Html.RadioButton("team", "developer", new { onclick = "showResult(this)"})
Tester :#Html.RadioButton("team", "tester", new { onclick = "showResult(this)"})
</div>
<div id="partialContainer"></div>
<script type="text/javascript">
function showResult(radio) {
var selected = radio.value;
if (selected == "developer")
document.getElementById("partialContainer").innerHTML
= document.getElementById("developerDiv").innerHTML;
else if (selected == "tester")
document.getElementById("partialContainer").innerHTML
= document.getElementById("testerDiv").innerHTML;
}
</script>
enjoy..

Resources