MVC3 button click event - asp.net-mvc-3

I should have 3 buttons in my view(Add, Save, Cancel). If I click these buttons they should hit relevant methods in the controller. How do i achieve button click event in MVC3? Can anyone provide me with an example? Suggest me if any better way.

There's no server side button click event in MVC 3, you'll need to work out which button was clicked based on the form values you get posted back. Have a look at this blog post for further info -
http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx

I'm really new to ASP.NET MVC but a way that I solved this was that I had a couple of buttons on my form and gave each of them a class, and then specified the data parameters for them, in this example I've got two properties from some item Val1 and Val2 for the first button and two for the second - Val1 and Val3:
<input type="button" value="Button 1" class='button1' data-val1="#item.Val1" data-val2="#item.Val2"/>
<input type="button" value="Button 2" class='button2' data-val1="#item.Val1" data-val2="#item.Val3"/>
and then I used some jquery to handle the click events and specified which action to call:
<script type="text/javascript">
$(function () {
$('.button1').click(function () {
var Val1 = $(this).data('val1');
var Val2 = $(this).data('val2');
$.ajax({
type: "POST",
data: "val1=" + Val1 + "&val2=" + Val2,
url: '#Url.Action("MyAction", "MyController")',
dataTyp: "html",
success: function (result) {
// whatever I did here on success
}
});
});
});
// rinse and repeat for the other button, changing the parameters and the action called.
</script>
This seemed to work pretty well for my needs.

The below button click event hits the relevent actionResult method in the controller
<input type="button" name="button" id="btnadd" value="Add" onclick="location.href='#Url.Action("ActionResultName", "ControllerName")'" >

Related

How do I get the value of a button to pass back to the server when using JQuery & AJAX?

I am using MVC3, Razor, C#, JQuery and AJAX.
I am using an Ajax call to postback a form to the server. I get all the form element values being passed back to the controller in:
[HttpPost]
public ActionResult Edit(Product myProduct, string actionType)
if (actionType == "Save")
save....
And in the View I have:
#using (Html.BeginForm("Edit", "RA", FormMethod.Post, new { #class = "editForm", #id = "frmEdit" }))
Form Elements:
<td>
#Html.HiddenFor(p=>p.Id)
<button type="submit" name="actionType" value="Save" >Save</button>
</td>
<td>#Html.EditFor(p=>p.Name)</td>
Some Ajax:
$('.editForm').on('submit', function () {
$.ajax({
url: this.action,
type: this.method,
data: $('#frmEdit').serialize(),
context: $('button', this).closest('tr'),
success: function (result) {
$(this).html(result);
}
});
return false;
});
Now I think the problem line is since I have seen quite a few posts about problem with JQuery and submitting button values:
data: $('#frmEdit').serialize(),
But I cannot get the button to submit an actionType of "Save". I just get null.
Thoughts greatly appreciated.
Thanks.
UPDATE:
My code seems to interfere with my JQuery listener ?? My code is:
<input type="submit" id="btn" name="btn" value="Save" onclick="document.getElementById('actionType').value = 'Save';"/>
From the documentation:
No submit button value is serialized since the form was not submitted using a button.
However you can add it by hand:
data: $('#frmEdit').serialize() + '&actionType=Save',
or
data: $('#frmEdit').serialize()
+ '&'
+ encodeURIComponent(button.name)
+ '='
+ encodeURIComponent(button.value),
where button is the <button> DOM element.

Reloading main view after button in PartialView is clicked

I have a partial view that the user can preform a search in, and the search results are shown in a select box. In my main view I have a section that is supposed to show the search results after a select button is pressed. Right now when I click the select button is loads the correct information into the correct model for my main view, but the main view doesn't change. When I click refresh, the page updates correctly. How do I make the page update automatically when a button is clicked in the plugin view?
My section in the main view (Index.vbhtml) in my main app:
#Section CUInfo
Credit Union Name: #Model.CUInfo.CUName
end section
Here is my controller method in my Plugin:
Function ChangeCUInfo(strCUName As String) As ActionResult
m_hostApp.CUInfo.CUName = strCUName
m_hostApp.blnPluginRefreshButtonPressed = True
Return View("Index", m_hostApp)
End Function
I've tried to set a boolean value in the hostApp object and then in my main razor view call this function if it is true:
#code
If Model.blnPluginRefreshButtonPressed = True Then
#<script type="text/javascript">
$(function () {
window.location.reload();
});
</script>
End If
Model.blnPluginRefreshButtonPressed = False
End Code
EDIT:
JS function called when the select button is clicked:
function loadCU(CUInfo) {
strCU = CUInfo.split('|');
strCUName = strCU[0];
$.ajax({
type: "POST",
url: "/CUContractNumberPlugin/ChangeCUInfo",
data: { "strCUName": strCUName }
});
}
Form that is used in the plugin view:
#Using (Html.BeginForm("ChangeCUInfo", "CUContractNumberPlugin"))
#<div id="LogoSigSearch" style="height:300px;width:500px;position:relative;">
<span style="display:inline-block;height:20px;width:166px;position:absolute;top:35px;left:5px;">Credit Union Name</span>
<br />
#Html.TextBox("strCUName")
<input type="submit" name="LogoSigSearch$ctl02" value="Search" id="LogoSigSearch_ctl02" tabindex="3" style="width:60px;position:absolute;top:5px;left:352px;" />
<input name="LogoSigSearch$ctl05" type="button" onclick="javascript:clearSearch()" value="Clear" style="position:absolute;top:35px;left:352px;width:60px;" />
<select size="4" name="LogoSigSearch$ctl06" id="LogoSigSearch_ctl06" tabindex="5" style="height:230px;width:342px;position:absolute;top:65px;left:5px;"></select>
<input type="button" name="SelectCU" value="Select" onclick="javascript:loadCU(LogoSigSearch_ctl06.options[LogoSigSearch_ctl06.selectedIndex].value)" tabindex="4" style="width:60px;position:absolute;top:65px;left:352px;" />
</div>
End Using
Are both buttons part of a form? A button won't invoke an action without you attaching it to script or making it part of a form with an associated action.
Use a partial view to render the results of the query, even on the main page load. This simplifies your development.
Add a jQuery event handler (jQuery.on()) to watch for the button click on your main page, or if the button is returned in the partial view, just use an on ready handler in your partial and attach a button.click() event, again using jQuery.
The jQuery event handler can take care of submitting the values of the query, posting to your controller, and displaying the results. I have a number of older articles here but they are still relevant to your question and demonstrate submitting data and fetching partials.
Your client-side code will end up looking something like this:
$("#your-button").click(function () {
var fetchUrl = '#Url.Action("ActionName", "Controller")';
$.post(fetchUrl, { searchParams: $("#your-search-box").val() })
.success(function (data) {
// replace the contents of the DIV with the results. 'data'
// here has whatever you sent back from your partial view
})
.error(function (data) {
// handle the error, use a DIV with some kind of alert message etc
});
});
Hope this helps some.

partial view not opening as jQuery UI Dialog

I need to open a partial view as dialog box on click of a button, basically add/ Edit scenario. My problem is that mu partial view does open but not as a dialog but at the bottom of the page.
Please see my code below:
I have an empty div on the page:
On the click of the button I call the below code:
function addSelectionActivate() {
var selectionID = 0;
$.ajax({
url: "AddEditSelection",
type: "POST",
data: "&selectionID=" + selectionID,
dataType: "html",
success: function (data) {
$("#addEditSelectionDialog").html(data);
$("#addEditSelectionDialog").dialog('open');
},
error: function (error) {
alert(error.status);
}
});
}
My controller has a method "AddEditSelection" which returns the result. But the partial view opens at the end of the page rather than as a dialog. Please help what I might b edoing wrong.
you need to add the partial in a seperate div contained in the dialog div.
eg:
<div id="DialogDiv">
<div id="AnotherDiv">
</div>
</div>
and register "DialogDiv" as dialog and load ur partial in the "AnotherDiv"

multiple button click in 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>

MVC 3: Why is jquery form.serialize not picking up all the controls in my form?

I am trying to create a situation where if a user clicks on an "edit" button in a list of text items, she can edit that item. I am trying to make the "edit" button post back using ajax.
Here's my ajax code:
$(function () {
// post back edit request
$('input[name^="editItem"]').live("click", (function () {
var id = $(this).attr('id');
var sections = id.split('_');
if (sections.length == 2) {
var itemID = sections[1];
var divID = "message_" + itemID;
var form = $("#newsForm");
$.post(
form.attr("action"),
form.serialize(),
function (data) {
$("#" + divID).html(data);
}
);
}
return false;
}));
});
But the form.serialize() command is not picking up all the form controls in the form. It's ONLY picking up a hidden form field that appears for each item in the list.
Here's the code in the view, inside a loop that displays all the items:
**** this is the only control being picked up: ******
#Html.Hidden(indexItemID, j.ToString())
****
<div class="datetext" style="float: right; margin-bottom: 5px;">
#Model.newsItems[j].datePosted.Value.ToLongDateString()
</div>
#if (Model.newsItems[j].showEdit)
{
// *********** show the editor ************
<div id="#divID">
#Html.EditorFor(model => model.newsItems[j])
</div>
}
else
{
// *********** show the normal display, plus the following edit/delete buttons ***********
if (Model.newsItems[j].canEdit)
{
string editID = "editItem_" + Model.newsItems[j].itemID.ToString();
string deleteID = "deleteItem_" + Model.newsItems[j].itemID.ToString();
<div class="buttonblock">
<div style="float: right">
<input id="#editID" name="#editID" type="submit" class="smallsubmittext cancel" title="edit this item" value="Edit" />
</div>
<div style="float: right">
<input id="#deleteID" name="#deleteID" type="submit" class="smallsubmittext cancel" title="delete this item" value="Delete" />
</div>
</div>
<div class="clear"></div>
}
It's not picking up anything but the series of hidden form fields (indexItemID). Why would it not be picking up the button controls?
(The ID's of the edit button controls, by the way, are in the form "editItem_x" where x is the ID of the item. Thus the button controls are central to the whole process -- that's how I figure out which item the user wants to edit.)
UPDATE
The answer seems to be in the jquery API itself, http://api.jquery.com/serialize/:
"No submit button value is serialized since the form was not submitted using a button."
I don't know how my action is supposed to know which button was clicked, so I am manually adding the button to the serialized string, and it does seem to work, as inelegant as it seems.
UPDATE 2
I spoke too soon -- the ajax is not working to update my partial view. It's giving me an exception because one of the sections in my layout page is undefined. I give up -- I can't waste any more time on this. No Ajax for this project.
You could try:
var form = $('#newsForm *'); // note the '*'
Update
Did you change the argument to $.post() as well? I think I may have been a little too simple in my answer. Just change the second argument within $.post() while continuing to use form.attr('action')
New post should look like this:
$.post(
form.attr("action"),
$('#newsForm *').serialize(), // this line changed
function (data) {
$("#" + divID).html(data);
}
);

Resources