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

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.

Related

asp.net mvc5 ajax with jquery

I am building a website online store I want when click the add to cart button then number of commodity to be stored in a session with ajax and the message "saved" is displayed But this don’t work and don't display "saved"
View :
<p>
<img src="images/a.jpg">
<input type="text" id="1232542">
<button class="art-button">add to cart</button></p><p id="resolt">
</p>
jQuery :
$('#btntaeid1').click(function () {
var number = $("#1232542").val();
$("#resolt").html('loding...');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Main", "AddToCart")',
data: { 'Number': number },
success: function(aaaa) {
$("#resolt").html(saved);
}
});
});
Session class
public class SessionCommodity
{
private string NumberCommodity;
public SessionCommodity()
{
}
}
AddToCart Action in Main controler
[HttpPost]
public ActionResult AddToCart(int Number)
{
var s = System.Web.HttpContext.Current.Session["cart"] as List<SessionCommodity>;
if (s == null)
{
System.Web.HttpContext.Current.Session["cart"] = s;
}
s.Add(new SessionCommodity {NumberCommodity = Number });
return Json(new {Added = true});
}
You are trying to call the ajax method when the button which has id of "btntaeid1" clicked. But your html content hasnt got that element. Either add the id attribute to the button element or change the click function to be fired when something exist is clicked.
View:
<p>
<img src="images/a.jpg">
<input type="text" id="1232542">
<button id="btntaeid1" class="art-button">add to cart</button></p><p id="resolt">
</p>
or the jquery part according to your post:
$('.art-button').click(function () {
var number = $("#1232542").val();
$("#resolt").html('loding...');
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Main", "AddToCart")',
data: { 'Number': number },
success: function(aaaa) {
$("#resolt").html(saved);
}
});
});

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);
}
})
}

knockout.js redirect in view model

I have the following code on cshtml page.
<div class="buttons">
<button type="button" id="export" class="export-inventory-button" onclick="location.href='#Url.Action("ExportInventory", "Inventory")'">EXPORT INVENTORY</button>
</div>
How do I make this work in my view model?
I think I almost got it, but need some help
<div class="buttons">
<button type="button" id="export" class="export-inventory-button" data-bind="click: exportInventory">EXPORT INVENTORY</button>
</div>
My viewmodel has this code:
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
$.ajax({ url: '/Inventory/ExportInventory', type: 'POST' }).done(function (data) {
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
I tried this, but I get errors:
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
$.ajax({ url: 'location.href="#Url.Action("ExportInventory", "Inventory")"', type: 'POST' }).done(function (data) {
window.location.href = responseText.url;
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
Can someone help me figure this out?
The way you're trying to pass in the url to the ajax call is probably not working the way you expect. Also, you wouldn't need the location.href= to be part of the url parameter in the $.ajax() call.
If your view model is coded in a script tag right in your cshtml page, you can try this:
<!-- cshtml razor view code for generating the html is above this line -->
<script>
var viewModel = {
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
//allow razor to build a javascript string for you when it renders the html
//when the browser parses this script, it will just see a simple string
var myURL = '#Url.Action("ExportINventory", "Inventory")';
//pass your variable to the jQuery ajax call
$.ajax({ url: myURL, type: 'POST' }).done(function (data) {
window.location.href = responseText.url;
//this line of code would never be called because the browser has navigated away from this page...
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
};
</script>
Load the page and view source. If the var myUrl = line is the correct URL to your controller as a string, then you know that razor kicked in and prepared that for you on render.

Dynamically added form ajax not work

I have a list of div's.
When I click on a button in a div I switch div content with partial view which contain form.
This is code that happens when I click on that button:
#Html.ActionLink("edit", "EditUserLanguage", "UserLanguage", new { userLanguageId = Model.UserLanguageId }, new { #class = "editButton" })
...
$(document).on('click', '.editButton', function (e) {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
var id = $(e.target).closest("div").attr("id");
$("#" + id).empty();
$("#" + id).append(html);
}
});
return false;
});
Html (partial view) that I add has:
#using (Html.BeginForm("UpdateUserLanguage", "UserLanguage", FormMethod.Post, new { id = "updateUserLanagegeForm" }))
{
...
This main view where is the list of div's and where I add this new partial view I have this code:
$(function () {
$('#updateUserLanagegeForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
}); //update
When I click on submit action method is invoked and I get new partial view returned but not via ajax.
I only get that partial view returned. alert("work"); is never called.
What could be the reason that this ajax call doesn't work?
submit handler is not being attached to form as form gets loaded after dom ready. So change your code to -
$('body').on('submit','#updateUserLanagegeForm',(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
This will attach handler to form even if it is added dynamically.

Replace the Ajax.ActionLink by the same functionality with jQuery

With asp.net mvc we can do an ajax call like this:
#{
var ajaxOpts = new AjaxOptions { UpdateTargetId = "main-content", OnBegin = "fctTabLoading", OnComplete = "fctTabLoaded", InsertionMode = InsertionMode.Replace };
}
#Ajax.ActionLink("my link text", "MyAction", "MyController", new { id = Model.RequestID }, ajaxOpts)
Which produce the following html:
<a data-ajax="true" data-ajax-begin="fctTabLoading" data-ajax-complete="fctTabLoaded" data-ajax-mode="replace" data-ajax-update="#main-content" href="/MyController/MyAction/19">my link text</a>
Now I would like to execute the same ajax call but from jQuery and I don't know how to proceed!
I would like something like:
$.ajax({
type: "Post",
url: myURL,
begin: fctTabLoading,
complete: fctTabLoaded,
mode: "replace",
update: "#main-content",
cache: false,
success: function () { alert('success'); }
});
I know the above ajax script won't work because 'mode' and 'update' are not recognized. So I am blocked.
It drives me crazy :(
Why I cannot use the MVC ActionLink? Because I first need to show a jquery dialog to let the user confirm then only do the ajax call in order to refresh a specific div on my page.
Any help is greatly appreciated.
Thanks.
You could start by replacing your Ajax link with a normal link:
#Html.ActionLink(
"my link text", // linkText
"MyAction", // actionName
"MyController", // controllerName
new { id = Model.RequestID }, // routeValues
new { id = "mylink" } // htmlAttributes
)
which will produce the following markup:
my link text
and then in a separate js file unobtrusively AJAXify it:
$(function() {
$('#mylink').click(function() {
$.ajax({
url: this.href,
type: 'POST',
beforeSend: fctTabLoading, // corresponds to your OnBegin callback
complete: fctTabLoaded, // corresponds to your OnComplete callback
success: function(result) {
$('#main-content').html(result);
}
});
return false;
});
});
As you know, the Ajax.ActionLink uses jquery.unobtrusive-ajax.js to execute the ajax links.
If you look at that file, you will see that the event handlers use jquery's live event binder. This binds the event listener to the document object. So, if you wanted to confirm before this event was triggered, you could bind directly to the element like the following:
$('#YOUR_ELEMENT').click(function () {
var confirmed = confirm("CONFIRM_MESSAGE");
if (!confirmed ) {
return false;
}
return true;
});
To use jquery dialog you could do the following:
function confirmDialog () {
$('#YOUR_DIALOG').dialog(
{ buttons: { "Ok": function() { return true; },
{ "Cancel": function() {return false;}
}
});
}
and then you would set confirmed in the previous function to confirmDialog().
***The dialog options may not be exactly what you want, but this should get you going.

Resources