How do I target a div when programmatically submitting and MVC Ajax form? - asp.net-mvc

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

Related

Refresh list and not page in MVC

I have a requirement where on the left side of the page there are links and in the center, there is a table so I have to refresh the table based on the link selected however it should not refresh page, I opted for Ajax action link, however, there are issues post the implementation and I realised that is not good from design perspective so could you please help me with some solution possibly code to achieve my requirement.
#Ajax.ActionLink("click me",
"GetContacts",
"Home",
new AjaxOptions
{
UpdateTargetId = "DepartmentDetails",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnSuccess = "OnAjaxRequestSuccess"
}
)
Move the table to a partial view and load it on click of the link. This will just refresh the partial view instead of the entire master page.
You can use jQuery Ajax. It doesn’t required to refer any additional script for partial load.
Example:
#using (Html.BeginForm(new { id = "DepartmentDetails" }))
{
#Html.TextBox("deptName ");
<input type="submit" value="List Department" id="btnList" />
<div id="divDepartmentDetails"></div>
}
#section Scripts{
<script>
$("#btnList").click(function (event) {
$.ajax({
url: "#(Url.Action("Department"))",
type: "GET",
data: { deptName: $("deptName").val() },
success: function (data) {
$("#divDepartmentDetails").html(data);
}
});
});
</script>
}

ASP.NET MVC 3 + jQuery Ajax JSON - Prevent JSON from opening in new page

I have an Action Method that returns a JSON-serialized object. The problem I'm having is that the JSON returned is opening in a new page, instead of being processed by the "success" function of the jquery.Ajax method.
Here's the controller action:
[HttpPost]
public ActionResult AddAssignment(AssignmentViewModel avm)
{
db.Assignments.Add(new Assignment
{
Name = avm.Name,
DueDate = DateTime.Parse(avm.DueDate),
CourseID = avm.CourseID,
IsComplete = false
});
db.SaveChanges();
avm.Course = db.Courses
.Where(x => x.CourseID == avm.CourseID)
.SingleOrDefault()
.Name;
return Json(avm);
}
Here's the View (form):
#model Fooburg.Mvc.Models.AssignmentViewModel
<h2 style="margin: 0 0 24px 0">Add Assignment:</h2>
#using (Html.BeginForm("AddAssignment",
"Assignments",
FormMethod.Post,
new { #id = "add-assignment-form" }))
{
<dl class="tabular">
<dt>Course:</dt>
<dd>
#Html.DropDownListFor(x => x.CourseID, new SelectList(ViewBag.Courses, "CourseID", "Name"))
</dd>
<dt>Assignment:</dt>
<dd>
#Html.TextBoxFor(x => x.Name)
</dd>
<dt>Due Date:</dt>
<dd>
#Html.TextBoxFor(x => x.DueDate, new { #class = "date" })
<script type="text/javascript">
$(function () {
$('.date').datepicker({ dateFormat: "mm/dd/yy" });
});
</script>
</dd>
</dl>
<p>
<input type="submit" value="Add Assignment" id="new-assignment-submit" />
</p>
}
And here's the javascript:
$(function () {
$('#add-assignment-form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
});
});
I have tried the event.stopPropogation() method, but didn't change my problem
EDIT: I've updated my javascript to the following, but I'm still getting the same result
$('#add-assignment-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
You need to return false; or event.preventDefault() to prevent the browser from submitting the form normally.
You have two options here,
Use Ajax.BeginForm() instead of Html.BeginForm() that you would use like
#using(Ajax.BeginForm( "AddAssignment", "Assignments",
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "output"})) {
...
}
and get rid of the javascript code.
Or call event.prevendDefault() in
$('#add-assignment-form').submit(function (event) {
// ...
event.preventDefault();
});
Just specify
return false;
after your $.ajax() call
UPDATE
$(function () {
$('#add-assignment-form input[type=submit]').click(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
});
Have you checked if there are other javascript errors on the page that might be causing this unexpected behaviour? I would suggest Firebug for FF or Javascript Console for Chrome.
Also, I've noticed that sometime FF has issues if you don't specify the script type, so make sure your type is set to "text/javascript".
hth,
-covo

Posting to action, mvc 3, not part of form

Can I post to action from view a filed of of my model ? Is is not part of the form. I just want to pass the myModel.someValue as argument to nextRelease action, hopefully without putting it anywhere in the form.
e.g.
View:
#model myModel
#using (Html.BeginForm("Search", "News", FormMethod.Get, new { id = "myform" }))
{
<div>myModel.someValue</div> //to show it has this field
<script type="text/javascript">
$('#nextbutton').click(function () {
$('#myform').attr("action", "/#controller.Language/news/nextRelease");
$("#submit").click();
});
</script>
}
Sure, you could use AJAX:
#model myModel
<script type="text/javascript">
$(function() {
$('#nextbutton').click(function () {
var url = '#Url.Action("NextRelease", "News")';
var dataToPost = #Html.Raw(Json.Encode(new { someValue = Model.SomeValue }));
$.post(url, dataToPost, function(result) {
alert('data successfully posted to server');
});
return false;
});
});
</script>
<button id="nextbutton">Next button</button>
or if you wanted to post not only a single property but the entire model:
var url = '#Url.Action("NextRelease", "News")';
var dataToPost = #Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dataToPost),
success: function(result) {
alert('data successfully posted to server');
}
});

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.

Is not the way I want PartialViewResult

I try something.I apologize in advance for my english.
My Action code;
public PartialViewResult showProduct()
{
var query = db.Categories.Where((c) => c.CategoryID == 4);
return PartialView("_EditCategory",query);
}
My view code:
#using (Ajax.BeginForm(
"showProduct",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "result"
}))
{
<input type="submit" value="Get" />
}
<div id="result">
</div>
When i pushed the submit button ( which value is get) the results return but in another page like http://localhost:57616/Home/showProduct but i want return to result div in index page.
Any one can help me?
So, how I handled this myself was something like this:
$(document).ready(function () {
var options = {
target: "#mytargetdiv",
url: '#Url.Action("Edit", "IceCream")',
};
$("#editIceCreamForm").submit(function () {
$(this).ajaxSubmit(options);
return false;
}
// other stuff
});
in other places, where I wanted to do in-place editing of things I'd do something like this:
<input type="button" id="someid" value="Edit" data-someid="#Model.SomeId"/>
and then some ajax like so:
$(function () {
$("#someid".click(function () {
var theId = $(this).data('someid');
$.ajax({
type: "GET",
data: "id=" + theId,
url: '#Url.Action("Edit", "Something")',
dataType: "html",
success: function (result) {
$('#targetdiv').html(result);
}
});
});
});
So, if you're not interested in using jQuery and want to use the MS Ajax stuff, are you including the MicrosoftAjax.js and MicrosoftMvcAjax.js files on the page? If you don't have those, I believe what will happen is it just does the default (non-Ajax) submit.

Resources