In my application I have a common layout for all the views, from one of the view(Index.cshtml) i have used Ajax.BeginForm to display another view as a response the code for this is
@using (Ajax.BeginForm("Edit", "Home", new AjaxOptions { UpdateTargetId = "content",InsertionMode=InsertionMode.Replace }))
now my problem is as a response the edit view is rendered as expected but the script block with in the edit view is not included and hence the javascript is not executed.
@model Test.Models.CARE
@{
ViewBag.Title = "Edit";
}
<script>
function s() {
alert("hi");
}
</script>
<h2 style="padding: 0px; margin-top: 0px;">
Edit</h2>
@using (Html.BeginForm("SaveForConfirmation", "Home"))
{
Plz help.
It’s bad practice to put javascript code in views, let alone partial views. So I would recommend you to externalize this javascript code in a separate function in a separate javascript file.
And then you could subscribe to the
OnSuccessevent of the Ajax.BeginForm helper:and then define the
editSuccessfunction in a separate javascript file:now in your partial view you should leave only what is supposed to be in a partial – markup. Get rid of any
<script>tags, you don’t need them. You don’t need any inline scripts. They only increase the size of your webpages and waste bandwidth as they cannot be cached by the browsers:;UPDATE:
If you have some poorly written javascript that depends on crap like ViewBag inside the partial then you could invoke the corresponding function from within the OnSuccess callback:
Notice how I have defined
OnSuccess = "s"wheresis the function that you have defined in your partial and which will be invoked in this case. But I repeat once again, this is a wrong approach and should only be used if you don’t have time to refactor your code properly.