I have a View 'Parent' in my application , I am using @Html.BeginForm & a submit button to save data of Parent view . I also have one partial view inside Parent view , I am trying to call ajax method(using jQuery) from partial view but each time it redirects me to action method of parent form.
Parent View
@using (Html.BeginForm("Test1", "Home", new { id = 1 }, FormMethod.Get))
{
@Html.Partial("TestPartial", Model)
<div>
<input id="Button1" type="submit" value="Parent" />
</div>
}
Partial View
<script>
function onClientClick() {
$.ajax({
url: "/Home/Test2",
type: "GET",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ID: 1 }),
cache: false,
success: function (data) {
alert('Success');
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
}
</script>
<div>
<input type="submit" name="submit" onclick="onClientClick()" value="Submit" />
</div>
Each time i am trying to call /Home/Test2 from Partial view it redirects me to /Home/Test1(Action of parent form)
The problem is in this line:
<input type="submit" name="submit" onclick="onClientClick()" value="Submit" />
The type is submit
therefore it is submitting the form and redirecting you to the Action in the parent.
In your partial view have a regular button
not a submit button
to request the AJAX
content:
<input type="button" onclick="onClientClick()" value="Ajax Call" />
You could also return false
however I believe using the standard button
rather than submit
is more suited in this context.
Return false
after calling the ajax... at the end of onClientClick
function
OR Re-Write your submit as
<input type="submit" name="submit" id="submit" value="Submit" />
and then in jquery bnd the click event as
$("submit").click(function(e){
e.preventDefault()
$.ajax({
url: "/Home/Test2",
type: "GET",
.
.
.
});
OR Change the input
type from submit
to button
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.