how can I check which submit button was pressed? - asp.net-mvc

I have a two submit buttons set up for form submission.
I'd like to know which submit button was clicked without applying a .click() event to each one.
One more thing I am using ASP.NET MVC 3 and want to get the clicked button name in Controller.
Here's the setup:
<a class="anchorbutton">
<input type="submit" value="Save" id="Save" class="hrbutton"/>
</a>
<input type="submit" value="Save & Next" id="SaveNext" class="hrbutton anchorbutton"/>
$('#form').live('submit', function (e)
{
e.preventDefault();
var form = $('#form');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
$.ajax({
url: 'url',
dataType: "html",
success: function (data) {
$("#div").html(data);
}
});
}
});
return false;
});
[HttpPost]
public JsonResult Post(FormCollection form, string submitButton)
{
}

well try binding the click event handler to the Save and SaveAndNext buttons like
$(document).delegate("#Save,#SaveAndNext","click",function(e){
console.log($(this).attr("id"));//here you will know which button was pressed
//next you can check if the form is valid or not
if($(this).closest('form').valid()){
//form is valid submit it ajax(ily)
}else{
//form is not valid
}
});
you can also cache the selector
var $this = $(this);

Give your buttons names:
<a class="anchorbutton">
<button type="submit" name="save" id="Save" class="hrbutton">Save</button>
</a>
<button type="submit" name="savenext" id="SaveNext" class="hrbutton anchorbutton">Save & Next</button>
and then your controller action could take those parameters with the same name and check if it has a value:
[HttpPost]
public ActionResult Post(string save, string saveNext, FormCollection form)
{
if (!string.IsNullOrEmpty(save))
{
// The Save button was clicked
}
else if (!string.IsNullOrEmpty(saveNext))
{
// The Save & Next button was clicked
}
else
{
// None of the submit buttons were used or clicked to submit the form.
// The user simply pressed the Enter key while the focus was inside
// some of the input fields of the form
}
...
}
Oh and by the way, the .live jQuery function is deprecated. Use .on instead.

Try
ButtonClick Event " OnClick="MyButton_Click" "

Related

How to open a popup and post data to controller simultaneously using ajax call in MVC

I'm trying to implement search functionality in my Form View. The search window opens in a popup (in a partialView) and asks for search queries(figure). Now the user enters all the search fields and POST request is made and eventually popup window displays a table of search result.
Form View (which has the button to open popup window)
#Ajax.ActionLink("Search current form", "SearchAction", new { #id = "SearchBtn" }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, OnSuccess = "openPopup" }, new { #class ="btn btn-primary"})<br />
<div id="result" style="display:none"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#result").dialog({
autoOpen: false,
title: 'Search Window',
resizable:0,
width: 1000,
height: 700,
modal: true
});
});
function openPopup() {
$("#result").dialog("open");
}
</script>
SearchForm View (implemented as partial view)
#using (Html.BeginForm("SearchAction", "ViewModel", FormMethod.Post, new { #id = "searchform" }))
{
//some form elements
<div class="text-center">
<input type="submit" value="Go" class="btn btn-primary"/>
</div>
}
<div class="alert-danger">#ViewBag.emptyResult</div>
#if (Model != null)
{
//display the search results
}
Now to retain the popup I have to bind Go button to a ajax action in the same way as Form View. Also by reading this How to pass formcollection using ajax call to an action? I came to know that Ajax actions posts JSON data into the controller as opposed to key value pair which is easily accessible by FormCollection. So my question is how do I implement submit button(Ajax.Actionlink) in my search form so that it posts data into controller using FormCollection and retains the popup window as well.
Turns out I just needed to define a placeholder for the result table in my search popup.
<div id="showData" class="text-center table table-bordered bg-light"></div>
Now get your search results using Ajax call
function GetSearchResult() {
var searchParams = [];
//get search queries from textbox ids
$.ajax({
type: 'POST',
dataType: "json",
traditional: true,
data: {
s: searchParams
},
url: "/{controller name} /{action}",
success: function (result) {
var col = [];
if (isJson(result)) {
var sR = JSON.parse(result);
//create a html table using javascript and fill it which the result you got
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table); //table is what you created dynamically using javascript
}
else {
alert("No results found, Please try again");
}
}
});
}
Add this action in your controller
[HttpPost]
public JsonResult AjaxMethod(string value, string Id)
{
var updatedList = GetSearchResults(); //get search result from your repository
return Json(updatedList);
}
And as far as creating a html table thorugh javascript is concerned this helped me a lot!

jQuery UI Autocomplete perform search on button click issues

I have a working UI Auto complete with jQuery. I wanted to change the way it worked. Instead of a new browser tab opening with the user selects a value from the list I wanted the user to first pick a value then click a search button to trigger the event.
It works but if you perform a search and then a second search it will trigger the previous URL and new URL at the same time. Also if you perform a search then click the search button without typing anything into the search input it triggers the previous search. Weird right? I'll add my code but I think a codepen example will help clarify what I mean.
The other issue I was having is I am trying to set up a custom alert if the value typed is not in the array but I get the invalid error message no matter what I type. I added that as well in the code. It is one of the if statements.
JS
var mySource = [
{
value: "Google",
url: "http://www.google.com"
},
{
value: "Yahoo",
url: "https://www.yahoo.com"
},
{
value: "Hotmail",
url: "https://hotmail.com"
},
{
value: "Reddit",
url: "https://www.reddit.com"
}
];
//Logic for ui-autocomplete
$(document).ready(function() {
$("input.autocomplete").autocomplete({
minLength: 2,
source: function(req, resp) {
var q = req.term;
var myResponse = [];
$.each(mySource, function(key, item) {
if (item.value.toLowerCase().indexOf(q) === 0) {
myResponse.push(item);
}
if (item.value.toUpperCase().indexOf(q) === 0) {
myResponse.push(item);
}
//Add if statement here to determine if what the user inputs is in the
// array
//and if not in the array give an error to #textAlert.
//Example
if (item.value.indexOf(q) != myResponse) {
$('#alertText').text("Invalid Search");
} else {
return false;
}
});
resp(myResponse);
},
select: function(event, ui) {
$('#appSearchBtn').one("click", function() {
window.open(ui.item.url);
$('#appsearch').val('');
return false;
});
}
});
});
//Input and ui text clears when clicked into
$(document).ready(function() {
var input = document.querySelector('#appsearch');
var ui = document.querySelector(".ui-helper-hidden-accessible");
input.onclick = function() {
input.value = '';
ui.textContent = '';
};
});
HTML
<p id="alertText"></p>
<div class="input-group">
<input type="text" id="appsearch" class="form-control autocomplete" placeholder="Application Search" />
<span class="input-group-btn">
<button class="btn btn-primary inputBtn" id="appSearchBtn" type="button">Search</button>
</span>
</div>
Here is a Code pen https://codepen.io/FrontN_Dev/pen/MEmMRz so you can see how it works. I also added how it should work and what the bugs are.
9/29/17 #0732
I resolved the issue with the event firing the same URL over and over but I still need help with the custom invalid search message that appears for every search even if the value is in the array.

How do I target a div when programmatically submitting and MVC Ajax form?

I'm using the MVC4 Ajax helper functions on a form and I'd like to submit the form from script.
The problem is when I call the submit function, it does not load into the proper div. Any thoughts?
#using (Ajax.BeginForm("NewGame", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "targetDiv" }, new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
<a class=button onclick="$('#newGameForm').submit();">New Game</a>
}
Clicking the standard submit button load the results of the call into the targetDiv. Clicking on the anchor replaces the current div.
The key is to prevent default browser behavior via .preventDefault() or to return false at the end of the event handlers.
This is how I'd do it:
<div id="targetDiv"></div>
#using(Html.BeginForm("NewGame", "Home", FormMethod.Post,
new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
}
<script type="text/javascript">
$(document).ready(function () {
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
type: $(this).attr("method") // "POST"
})
.done(function(result) {
$("#targetDiv").html(result);
})
.fail(function((jqXHR, textStatus, errorThrown) {
// handle error
});
});
});
</script>
If you insist on using an anchor <a>...
New Game
<script type="text/javascript">
$(document).ready(function() {
$("#submit-link").on("click", function(e) {
e.preventDefault();
$("#newGameForm").submit();
});
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
...
});
});
</script>
Edit There is also an AjaxHelper.ActionLink method. If you're already using the AjaxHelper in other parts of your code you might want to stick with that.
Pseudo Code.
<a class=button onclick="PostAjax();">New Game</a>
function PostAjax(){
$.ajax({
url:"Home/NewGame",
data:$('#newGameForm').serialize(),
DataType:"HTML", // assuming your post method returns HTML
success:function(data){
$("#targetDiv").html(data);
},
error:function(err){
alert(err);
}
})
}

Load partial view into div on button click without refreshing page

I know this question might be repeated but my query is different let me explain, I have a drop down in page and by selecting value in drop down list,and I click on submit button.. I want by click on submit button I need to load partial view in tag that is list of records of selected drop down list value.
i tried this :
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Content("~/Search/MDLNoDataList")',
data: mdlno,
success: function (data) { $("#viewlist").innerHtml = data; }
});
});
but not getting result And I m using these many jquery plugins
<script src="../../Scripts/jquery-migrate-1.0.0.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
If i understand correctly, below is what you need to do.
HTML Example:
<div id="records">
</div>
<select id="ddlRecordType">
<option value="1">Type 1</option>
<option value="2">Type 2</option>
</select>
<input type="submit" value="Load Records" id="btn-submit" />
jQuery Code
$(document).ready(function(){
$('#btn-submit').click(function(){
var selectedRecVal=$('#ddlRecordType').val();
$('#records').load('/LoadRecords?Id='+selectedRecVal);
return false; // to prevent default form submit
});
});
Here ?Id= is the query string parameter passed to server to get
the selected item in dropdown.
Edit: The below answer was added, as the question content changed from initial post
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("MDLNoDataList","Search")',
data: mdlno,
success: function (data) {
// $("#viewlist")[0].innerHtml = data;
//or
$("#viewlist").html(data);
}
});
return false; //prevent default action(submit) for a button
});
Make sure you cancel the default action of form submission by returning false from your click handler:
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("MDLNoDataList", "Search")',
data: mdlno,
success: function (data) {
$("#viewlist").html(data);
}
});
return false; // <!-- This is the important part
});
And if you are using the WebForms view engine and not Razor make sure you use the correct syntax to specify the url:
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '<%= Url.Action("MDLNoDataList", "Search") %>',
data: mdlno,
success: function (data) {
$("#viewlist").html(data);
}
});
return false; // <!-- This is the important part
});
If you do not return false, the form is simply submitted to the server when you click on the submit button, the browser redirects away from the page and obviously your AJAX call never has time to execute.
You will also notice some improvements I made to your original code:
Using the Url.Action helper when pointing to a server side controller action in order to take into account routes defined in your application.
Using jQuery's .html() method instead of innerHTML to set the contents of a given element.
You need AJAX for this purpose.
$.get(url, data, function(data) { $(element).append(data) });
and Partial View that is vague.
element {
overflow:hidden;
}

jQuery not submitting my form to an asp.net mvc controller

I'm trying to submit a form via ajax to an MVC controller.
HTML
<% using (Html.BeginForm("AskQuestion", "Home", FormMethod.Post, new { id="submitquestion"})) {%>
jQuery
$("#submitquestion").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: '<%= Url.Action("AskQuestion", "Home") %>',
type: "Post",
data: form.serialize(),
success: function(result) {
if (result.success) {
//success method
}
}
});
I'm getting no javascript errors, and my controller is not getting hit when I set a breakpoint. However, if I just set this:
$("#submitquestion").submit();
The form submits.
What am I doing wrong? I want to submit the form via .ajax
Add new html button to submit and wirte your ajax submit in the click event like this,
$("#yourButton").click(function(event) {
event.preventDefault();
var form = $('#submitquestion');
$.ajax({
url: '<%= Url.Action("AskQuestion", "Home") %>',
type: "Post",
data: form.serialize(),
success: function(result) {
if (result.success) {
//success method
}
}
});
});
for submitting via ajax. add a button to html form
<input type="button" name="button" value="Test" id="test" />
And your jquery script should be like this,
$('#test').click(function () {
var formCollection = $(this).parents('form').serialize();
$.post('your url', formCollection, function (result) {
alert(result);
});
});
Hope this helps.

Resources