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)
Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .
You can render a partial view using Html. Action helper method. Like Html. RenderAction requires controller child action method which return PartialViewResult.
To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view. It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.
A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With