I'm doing a site using MVC 4. It's a site that list musics and the user can create a playlist (like a cart shopping).
I have for every music this action link that should be executed in Ajax:
#Ajax.ActionLink("Adicionar à Playlist","AddPlaylist", new { id = item.MusicaID }, new AjaxOptions {UpdateTargetId="playlist", InsertionMode=InsertionMode.Replace})
The action method from the controller returns a PartialView (the cart of playlist) and only that should update but instead of getting the whole page with that part updated I get a partial view and nothing more on the page.
This is the part where I render the PartialView:
<section id="playlist">
#Html.Partial("_PlaylistPartial")
</section>
Shouldn't this work like I have?
Make sure you have included
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
in your view
It was a stupid thing.
First my include of jquery.unobtrusive-ajax.min.js didn't work like I have:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
So I put like this:
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
And still wasn't working, because I also need to include the JQuery files:
#Scripts.Render("~/Scripts/jquery-1.7.1.js")
#Scripts.Render("~/Scripts/jquery.1.7.2.min.js")
This way it works :)
A little late to the party but I just had a similar problem. The solution was to add this line to _Layout.cshtml:
#Scripts.Render("~/bundles/jqueryval")
First, install Microsoft.JQuery.Unobtrusive.Ajax from NuGet Manager and later include ~/Scripts/jquery.unobtrusive in BundleConfig after including jquery-{version}.js; which will look something similar to this:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery.unobtrusive*));
Related
I trying to study .net core with a test project.
In this project there is a user javascript javascript file called "booklist.js" that call some functions like edit and delete button.
For some strange think any modifications of this file don't do any effect.
After delete this file, the project continue to work.
But if i disable these lines:
#section Scripts{
<script src="~/js/bookList.js"></script>
}
on the view page the project not read the data.
I'am new with MVC and I don't have any idea about.
Can you help me please ?
Thanks !
One of the reasons of this issue could be browser caching the old js in file, as a solution is to append a parameter to your js source like a timestamp
Then your js tag becomes:
<script type="text/javascript" language="javascript">
var versionUpdate = (new Date()).getTime();
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "~/js/bookList.js?v=" + versionUpdate;
document.body.appendChild(script);
</script>
Reference: https://www.c-sharpcorner.com/article/how-to-force-the-browser-to-reload-cached-js-css-files-to-reflect-latest-chan/
or
You can use the new feature in .Net Core
asp-append-version="true"
Then your js tag becomes:
<script src="~/js/bookList.js" asp-append-version="true"></script>
Reference: https://www.c-sharpcorner.com/blogs/aspappendversion-feature-in-asp-net-core
I have a problem with rendering JavaScript file in _Layout.cshtml.
#section Scripts {
<script src="#Url.Content("~/Scripts/Custom/productsSuggests.js")"></script>
}
When I paste it to Index.cshtml (Home) it works, but only on this page. I need this script to work globally. I have partial view SearchBox in HomeViews catalog, and Controller Action in HomeController.
Because you are in the _Layout.cshtml view, it is likely the top level view. A section is a placeholder in a parent view.
Instead of your current code, try
#Scripts.Render("~/Scripts/Custom/productsSuggests.js")
In the Layout.cshtml you can use: #Scripts.Render("YOUR BUNDLES")
When will be add layout to another page this bundle will be global work.
In _Layout.cshtml is it possible to determine what View is going to be rendered in #RenderBody() ?
You can get the View (i.e. Index.cshtml) through ((RazorView)ViewContext.View).ViewPath
Example for your needs:
<script type="text/javascript" src="~/Content/Scripts/#(Path.GetFileNameWithoutExtension(Server.MapPath(((RazorView)ViewContext.View).ViewPath))).js"></script>
If you need your actual View (i.e. _Layout.cshtml), you can use VirtualPath instead.
Old answer
Reading your comments, you want to add a
<script ...>...</script>
depending on the view but outside of #RenderBody()?
Then put
#RenderSection("Scripts", required:false)
and in your view define the section like
#section Scripts {
<script ...>...</script>
}
So you don't need to maintain your _Layout.cshtml since every View defines their own scripts.
Here is an easy explanation: http://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts-and-sections-with-razor
What you can do is check Html.ViewContext.RouteData.Values. That's a dictionary with controller, action, and id (as necessary).
Read this article and it will solve your problem.
Edit
RenderBody
What is RenderBody?
In layout pages, renders the portion of a content page that is not
within a named section. [MSDN]
How RenderBody works (graphical presentation)?
The #RenderBody() renders the view controlled by the controller. so if your controller is like this.
public class HomeController : Controller
{
public ActionResult Index() // Renders File /Views/Home/Index.cshtml
{
return View();
}
}
Then the public ActionResult Index() Index.cshtml will be the view it will render located int the /Views/Home folder.
You can add to the Index.cshtml or _Layout.cshtml view to render other Views or partialViews By adding #Html.Partial("_MyView") as shown below.
#Html.Partial("_LayoutHeaderHeader")
#Html.Partial("_LayoutHeaderNavbar")
Sometimes it is easy to setup a few layout pages to call from different Views.
If you want to call scripts to you View you should always create a _PartialView and place your scripts in the partial view and call that View at the bottom of your View like this #Html.Partial("_MyView") and the scripts will set properly.
Here is a good tutorial. http://www.codeproject.com/Articles/698246/ASP-NET-MVC-Special-Views-Partial-View-and-Layout
If you derive all your models from a base model then you could add a property to you base model that returns the controller name, which you can get using
this.RouteData.Values["controller"].ToString();
It would be even better if you had a BaseController class because you could put this in the constructor and never have to touch it again.
Since you would be returning a descendant of the base Model to your index page which has the controller name, now you could use some scheme base on #Model.ControllerName. If your controller services multiple views the property could be updated to indicate a certain view name.
I don't think you can get the name of a Partial inside the index unless you use jquery and by that point the page resources have already been loaded.
Edit: One other trick would be to create your own version of #Html.Partial() HtmlHelper class. So you have #Html.MyPartial("ViewName") and inside that method call the internal function that generates Html.Partial and then inject your dependencies.
EDIT: I just read your comments about the issue and think that the better way is using the code snipplet provided by #Matt in another answer.
You can use the #section razor statement inside your view to inform wich script should be loaded.
Layout template placeholder
#RenderSection("scripts", required: false)
View Code
#section scripts {
<script src="~/Scripts/custom-imgedit.js"></script>
}
The example above inform that the custom-imgedit.js will be loaded in the render section placeholder. Note: You can even use bundles like #Scripts.Render("~/bundles/myCustomScripts")
I have downloaded the TinyMCE.MVC.Jquery and TinyMCE.MVC.Jquery.Sample into a new MVC.NET 4 project, however I cannot seem to get it to show in the sample TinyMCESampleJQuery cshtml page.
I only changed the
content_css: "#Url.Content("~/Content/Site.css")",
to point to my stylesheet and added the jquery and tinymce references
<script src="#Url.Content("~/Scripts/tinymce/jquery.tinymce.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
Do I need to do anything else to get it to work?
Ok so I tried something and this worked!
I removed the jquery link from my tinymce cshtml, and moved the jquery scripts bundle in the layout page to the and that worked
Are you referencing there stylesheet and have you added the required images into your project?
Just trying to wrap my head around the Ajax helper in Razor -- Probably overlooking something simple.
The following code is directing my current tab to /Music/SearchBand rather than returning the partial to my div.
I've got this in my View:
#Ajax.ActionLink("click me","SearchBand",
new AjaxOptions {
UpdateTargetId = "replaceThisDiv"
})
<div id="replaceThisDiv"></div>
And this in my controller:
public ActionResult SearchBand()
{
return PartialView("_bandResults");
}
The #Ajax. ... helpers jut add some additional data- attributes to the generated HTML which in itself won't do any ajax requests (that's why the link "just" navigated to a different page).
To make it work porperly it needs some client side javascript functions which will fire the actual ajax requests with the use of the pregenerated data- attributes.
These js functions are in the Sripts/jquery.unobtrusive-ajax.min.js file:
So you need to include this JS file on every page where you plan to use any of the #Ajax. ... helpers:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>