Milo
Milo

Reputation: 318

execute javascript function from controller in MVC 3

I got an action result inside a controller and i need to display Modals from bootstrap-modal the problem is... .

ScriptManager.RegisterStartupScript isn't working like in old asp.net

there is a solution to this? I'm new to mvc.

Upvotes: 1

Views: 7102

Answers (2)

Milo
Milo

Reputation: 318

Ok, the easiest solution for registering javascript from the controller was quite obvious, but frustrating for someone who's new to the pattern:

Using named sections we find a place for put the javascript

You can use [Named Sections][1].

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js)">
    @RenderSection("JavaScript", required: false)
</head>

and this code for the view

_SomeView.cshtml

@section JavaScript
{
    @Html.Raw(ViewBag.message)
}

and in the controller we return

ViewBag.message = @"<script type='text/javascript' language='javascript'>alert(""Hello World!"")</script>"; ;

Upvotes: 4

Vytalyi
Vytalyi

Reputation: 1695

In ASP.NET MVC scripts are not registered in controller actions. There's a separation between controllers and views. So you could directly put the script in the corresponding view:

Upvotes: 0

Related Questions