Ajax.ActionLink in MVC3 not working - c#

I'm developing an Asp.net MVC3 website from VS2012RC. I'm trying to create a partial view to the website using Ajax Actionlink. But it is not working. After trying everything I know with my team and a lot of searching, I then tried it on a TestProject. To my further depression that is also not working. I have tried to work around this for a long time and now I'm calling SO.
This is how I created my test project. Please let me know whether I am making a mistake or this is a fault in my machine.
I have created an MVC3 empty Project with html5 semantic markup and with the view engine of Razor.
Then I added a Home controller to my project and created a view for View() action.
Then I created another action TestAjax().
Then I Created a partial view in the Home Folder in Views
Folder.
This is my Index view:
#{
ViewBag.Title = "Index";
}
<div>
#Ajax.ActionLink("This is a test ajax","testAjax",new AjaxOptions{ UpdateTargetId = "TestAjax" ,HttpMethod ="GET",InsertionMode =InsertionMode.InsertAfter})
</div>
<div id ="TestAjax">
</div>
Partial View is :
<h1>Testing testing testing testing</h1>
Now what I expect is that when I click the link the header hast to appear below the link in the TestAjax division. But what actually happens is in home page the link appears. When I click the link, it will go to the "/Home/testAjax" and display only the partial view. There is no partial view.
Can you tell me what is the wrong with this procedure.
EDIT:
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/modernizr-2.0.6-development-only.js")" type="text/javascript"></script>
<script src="#Url.Content(" ~/Scripts/jquery.unobtrusive-ajax.js")" type = "text/javascript"> </script>
</head>
When I check the resources in the webpage of the view Index():
This is a test ajax

Referenced the ~/Scripts/jquery.unobtrusive-ajax.js js file was not in my layout/view. Since I was not familiarized with ajax. So, people who are new to ajax in MVC and came here by Googling, First check this reference mentioned above is in your layout/view.

Related

Issue getting started with FullCalendar in ASP.Net Core

For a reason or another, I really could not set up the FullCalendar.io for my ASP.Net Core project Razor Page. The documentation is also pretty poor imho so I will highly appreciate any tips on what I should do.
Firstly, I created the CalendarController.cs. The View that should show the calendar at this point is Index and I kept the controller method empty, like this:
public ActionResult Index()
{
return View();
}
The Index.cshtml is taken from here: https://fullcalendar.io/docs/initialize-globals
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<link href='fullcalendar/core/main.css' rel='stylesheet' />
<link href='fullcalendar/daygrid/main.css' rel='stylesheet' />
<script src='fullcalendar/core/main.js'></script>
<script src='fullcalendar/daygrid/main.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ]
});
calendar.render();
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
If I run my project and go to Calendar/Index, the page is blank. What step did I miss? On the getting started page, they state that a package has to be installed. The way I did was Nu-Get Package Manager -> Install Jquery.FullCalendar - is this the wrong way? I tried running this npm install --save #fullcalendar/core #fullcalendar/daygrid in the Package Manager Console but it didn't work out.
Any help regarding this is highly welcomed, as I said. Sorry for posting such a thing with all the documentation out there! I just couldn't figure it out coming from them.
EDIT: I also get the following warnings in the console:
C:/Users/user/source/repos/Intersection/Intersection/Views/Calendar/fullcalendar/core/main.js' not found. and 'C:/Users/user/source/repos/Intersection/Intersection/Views/Calendar/fullcalendar/daygrid/main.js' not found.
I think your problem is here:
<link href='fullcalendar/core/main.css' rel='stylesheet' />
<link href='fullcalendar/daygrid/main.css' rel='stylesheet' />
<script src='fullcalendar/core/main.js'></script>
<script src='fullcalendar/daygrid/main.js'></script>
I dont know wheres located your view, but in this instruction you are telling to look for the scripts in the same level as you are, which probably it is wrong; because you will have on the wwwroot folder, so something like should work, thats why it is telling you: "Couldnt file that file" , becasue theres no file in that location:
<link href='~/fullcalendar/core/main.css' rel='stylesheet' />
<link href='/wwwroot/yourPaht/fullcalendar/daygrid/main.css' rel='stylesheet' />
<script src='~/wwwroot/yourPath/fullcalendar/core/main.js'></script>
<script src='/fullcalendar/daygrid/main.js'></script>
Try that 4 ways and let us know!!
Where did you put the JavaScript and CSS files for fullcalendar? Seems like it's looking for them underneath the views folder here:
/Views/Calendar/fullcalendar/daygrid/main.js
I'm guessing they are actually installed at the root of your project or under a /content or /scripts folder or something, so you'll need to update the script and link tags for your js and css files to point to the right place.
maybe you can try to download libary
put js file and css file to ~/content or ~/script

Can a view selectively populate sections that appear outside the view in ASP.NET mvc?

I'm making a simple site with bootstrap and .net core mvc (v3.0). Because most of the pages reuse the bootstrap container, I decided to put that in the layout file, so that I wouldn't be repeating the same setup everywhere.
This has the downside that if a view needs fixed elements, those end up getting fixed to the container, not the viewport.
I'm wondering if it's possible to call some sort of syntax inside the view.cshtml file that could cause a section to be rendered in the _Layout.cshtml file (sorry if this has been answered, but I wasn't sure what to search for).
For instance
_Layout.cshtml
#using Microsoft.Extensions.Hosting
#inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment _environment
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"]</title>
</head>
<body>
#* this div only gets rendered based on logic inside the view*#
<div id="conditionalViewDiv">
</div>
<div class="content container-fluid pl-0 pr-0 moveable" id="containerMain">
<main role="main">
#RenderBody()
</main>
</div>
#RenderSection("Scripts", required: false)
</body>
</html>
and then in SomeView.cshtml
#{
ViewData["Title"] = "title";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#MadeUpRenderCommand("conditionalViewDiv")
#*other view stuff*#
Thank you for any help.
According to the docs, View components are intended anywhere you have reusable rendering logic, similar to partial views, but they're much more powerful. The main difference is when you use partial view you still have dependency on controller while in View Component you don't need a controller. So there is a separation of concern.
A view component is a C# class that provides a partial view
with the data that it needs, independently from the parent view and the action that renders it.
Good enlightening examples can be found, particularly:
https://www.c-sharpcorner.com/article/working-with-view-components-in-asp-net-core-mvc/
https://jakeydocs.readthedocs.io/en/latest/mvc/views/view-components.html
Hope this helped.

$ is not defined in view

I'm working on ASP.NET MVC 5. I have a viewstart.cshtml and imported the reference for my jquery like this
<!-- jQuery and Bootstrap JS-->
<script src="~/Scripts/jQuery/jQuery-2.1.4.min.js"></script>
<script src="~/Scripts/Bootstrap/js/bootstrap.min.js"></script>
In my view for HomeController I have alert function on document ready but there is an error that says $ is not defined.
But when I import the jquery directly to the view of my HomeController, it works fine. Why is that? The view of my HomeController is actually using the viewstart.cshtml that has the reference for jquery. Am I doing the correct way to import all my js/css files in Layout.cshtml? thanks for any help
In my View for HomeController if I reference the jquery directly, there is no error and it's working fine. But I want to do it once so all of the views don't need to reference it.
see below code:
#{
ViewBag.Title = "Welcome";
}
<script src="~/Scripts/jQuery/jQuery-2.1.4.min.js"></script>
<script>
$(function () {
alert("hello francis!")
})
</script>
<h2>WELCOME !!</h2>
It looks like you're loading your custom scripts before jquery.
Make sure you have something like this in Layout.cshtml (not _ViewStart.cshtml) somewhere between #RenderBody and </body>:
<script src="~/Scripts/jQuery/jQuery-2.1.4.min.js"></script>
<script src="~/Scripts/Bootstrap/js/bootstrap.min.js"></script>
#RenderSection("scripts", required: false)
and in the view you have to include your scripts into scripts section like:
#section scripts {
<script>
//your custom scripts here
</script>
}
This will ensure you that jquery will be loaded before your scripts.
Anything placed into section in the view will not be rendered during view render in RenderBody, and will be rendered only in RenderSection.
So jquery is loaded first in layout file, and only then section from the view containing your custom scripts that uses jquery being rendered.
usually you should use bundling to get jquery working.
inside the App_Start folder there's a file called BundleConfig.cs. Place the required jquery libs inside your scripts folder and update the bundle config file as follows:
public static void RegisterBundles(BundleCollection bundles)
{
// The jQuery bundle
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
//"~/Scripts/jquery-1.9.1.*",
"~/Scripts/jquery.min.js"
//"~/Scripts/jquery-ui-1.10.2.custom.js"
));
bundles.IgnoreList.Clear();
bundles.IgnoreList.Ignore("*.intellisense.js");
bundles.IgnoreList.Ignore("*-vsdoc.js");
bundles.IgnoreList.Ignore("*.debug.js", OptimizationMode.WhenEnabled);
}
in your Layout.cshtml right in the <head> tag area place the following piece of code to render your bundles defined:
#Scripts.Render("~/bundles/jquery")
You should now be able to use jQuery as expected.
This line:
<script src="~/Scripts/jQuery/jQuery-2.1.4.min.js"></script>
runs on the client's end.
The tilde (~) is the way to get to the server's root directory.
You can use url's with a tilde(~) on you server (e.g. using Server.MapPath) but they shouldn't be used on the client's end.
You can either create a relative url or an absolute url on your client, but don't use the tilde (~).
Your error ($ is not defined) means that JQuery has not been loaded. Either:
You didn't load JQuery correctly - check you url (easy to with the dev tools).
You are using the JQuery before it was loaded.
Go to Views/Shared/_Layout.cshtml and move this piece of code:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
from the body tag to the head tag and that should look like this:
...
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")/
#RenderSection("scripts", required: false)
</head>
...
...For me personally that worked out fine, there is no more need to embed direct references to jquery in each html page.

Using tabs in asp.net mvc with jquery ui

I am trying to create tabs in my mvc application using jquery ui.
I tried the following code:
<script src="../../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#tabs').tabs();
});
</script>
<div id="tabs">
<ul>
<li>Exploded pie slice</li>
<li>Normal pie chart</li>
</ul>
<div id="tabs-1">#(Html.Partial("PartialView1"))</div>
<div id="tabs-2">#(Html.Partial("PartialView2"))</div>
</div>
I saw something like the above code in jquery ui demo. Please advice me what I'm missing in my code because I only get two links instead of tabs and my two partial view pages are displayed in the index page.
Thanks,
Anandaraj
You haven't included the jQuery UI CSS file.
Either use the default skin, or pick one, or even build your own.
Bear in mind that you'll need all the images too, so follow my second link to download the whole theme (either an existing one or one you have built).

Including Javascript only if it has not yet been included in .NET MVC

In a .NET MVC partial view, I'd like to do something like this:
<% ScriptCollection.RequireScript("path/to/script.js"); %>
That would require a method in the ScriptCollection object that looks like this:
public void RequireScript(string src)
{
if (!_List.Contains(src))
_List.Add(src);
}
Then, in my Master page, I would have something like this:
<html>
<head></head>
<body>
<!-- Content would go here -->
<% foreach (var script in ScriptCollection) { %>
<script type="text/javascript" src="<%= script %>"></script>
<% } %>
</body>
</html>
My question is this:
How can I make the ScriptCollection object available to be updated by a partial view and also available to be used by a Master page?
Edit:
I do not want to add the required scripts in a controller, nor do I want to use a strongly typed Master page. Though suggestions on doing so are welcome if those methods are considered a best practice.
Edit #2:
This would be easy with extension properties. I could just give the HtmlHelper class the ScriptCollection property. Am I missing something like this that already exists?
I checked out the Telerik assemblies. They're a little overkill for what I need. Also, the open-source license (GPL v2) isn't the type I'm looking for.
I started a project licensed under the MIT open-source license and am hosting it on Google Code. It's a lightweight solution to my problem.
code.google.com/p/script-keeper
You could take a look at Telerik's ScriptRegisterBuilder class implementation which does exactly what you want. Or you can just use it as well. In addition it also has support for:
Combining multiple JS files into one which result in less requests by the browser.
Compressing JS files.
HTTP Caching.
Content Delivery Networks.
release/debug versions of your JS resources depending on your build mode.
Now even when you don't use any of the other stuff Telerik provides you can use the ScriptRegisterBuilder class but then it's advised to disable the automatic jquery & jquery validation script registration. See also the link provided.
Also take a look the StyleSheetRegistrarBuilder class. This is the nephew of the ScriptRegisterBuilder class and handles the CSS assets.
I did noticed the MVC2 tag in your question but my simple example uses razor and is just for making the point. It shouldn't be hard to make it work for MVC2/ASPX as well. Otherwise let me know.
Master
#using Telerik.Web.Mvc.UI
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
#Html.Telerik().StyleSheetRegistrar().DefaultGroup(group => group.Add("~/Content/Site.css"))
</head>
<body>
#RenderBody()
#Html.Telerik().ScriptRegistrar().jQuery(false).jQueryValidation(false)
</body>
</html>
Partial View
#using Telerik.Web.Mvc.UI
#{
ViewBag.Title = "Home Page";
Html.Telerik().StyleSheetRegistrar().DefaultGroup(group => group.Add("~/Content/Site2.css"));
Html.Telerik().ScriptRegistrar().DefaultGroup(group => group.Add("~/Scripts/Test.js"));
}
<h2>#ViewBag.Title</h2>
<p>
Bla bla bla
</p>

Categories