I have an MVC 2 application hosting on an IIS6 server. I have already done all the routing tweaks so that it can browse in the environment. The problem is however, that I have a dynamic partial view creation aspect, where a partial view is loaded each time an add button is clicked. Using Javascript and a controller, I call the partial vie and add it to a table each time.
Javascript Code
<script type="text/javascript">
$(function() {
$("#btnAdd").click(function (e) {
var itemIndex = $("#container input.iHidden").length;
console.debug("itemIndex : "+itemIndex);
e.preventDefault();
var URL = "/WorkOrder/NewItem/" +itemIndex;
$.get(URL,function(data){
$("#container").append(data);
});
});
});
and the controller is
public ActionResult NewItem(int id)
{
var interest = new ItemModel { index = id };
return View("_NewItem", interest);
}
Quite simple really. The funny thing is that it works when in the test localhost environment, but as soon as i deploy it to production, the btnAdd function does nothing. After using the inspect element Network debugging tool, I discovered that the network is returning a 404 error for the partial view.
Do i have to tweak the routing tables more to make them recognize the routing regime i am trying to implement?
Try using Url.Action method instead of just hard coding the URI and pass the data using data parameter.
Example:
var URL = '<%= Url.Action("WorkOrder", "NewItem")%>';
$.get( URL,
{id: itemIndex}
function(data){
$("#container").append(data);
});
Related
I am using google app scripts on google sites. I have created a navigation menu, and I embedded it into the page. I want to get the pageURL() from google scripts and retrieve it in my JavaScript page. I tried using the scriptlet to get the value, but it doesn't execute. Here is what I have so far. How can I get access to values in google app scripts and use them in my JavaScript function?
google script (.gs)
function getPageName(){
var site = SitesApp.getSite("site.com", "sitename");
var page = site.getChildren()[0];
var pageName = page.getUrl().split("/").splice(-1)[0];
return pageName;
}
javascript file
var pageName = <?!= getPageName()?>; // doesnt execute, need to get page url
if(pageName == linkName){
// add class here.
}
Since google loads the apps script as an iframe, I tried doing window.location.href, but it doesn't work either. The page name ends up being the name of the google app instead.
An alternative to using scriptlets is to use google.script.run (Client-side API)
It's pretty easy to use. In your case, it should be like this
code.gs
function getPageName(){
var site = SitesApp.getSite("site.com", "sitename");
var page = site.getChildren()[0];
var pageName = page.getUrl().split("/").splice(-1)[0];
return pageName;
}
Javascript File:
function onSuccess(receviedPageName)
{
if(receviedPageName== linkName)
{
// add class here.
}
}//onSuccess
google.script.run.withSuccessHandler(onSuccess).getPageName();
withSuccessHandler(function) is executed if the server-side function returns successfully or withFailureHandler(function) is executed if a server side function fails to complete the task it was assigned.
Give it a try :)
There are many older examples with this kind of syntax (from the question):
Here's a typical example of what you should never do:
<script type="text/javascript">
$.ajax({
url: '/home/index'
});
</script>
and here's how this should be done:
<script type="text/javascript">
$.ajax({
url: '#Url.Action("index", "home")'
});
</script>
Running an ASP.NET MVC app from a virtual directory in IIS7
I then found UrlHelper configuration is more difficult than in previous versions of MVC,
Unable to utilize UrlHelper
Are the Url Action methods "gone" or not what should be used now? Does Core want URL rewriting? How do I create a dynamic url string in Core 1.1 for JavaScript the "Core" way? I could build it manually and pass it to my View, but that is not what I wanted to do.
(no jQuery please, and yes I know the question above has jQuery)
Edit: In my JavaScript I have,
var xhr;
xhr = new XMLHttpRequest();
var url = //this is what I want Asp.Net to generate. Currently I manually build it within the JavaScript. It should be,
var url = 'Home/Index' //this can change possibly depending on where the application is deployed.
I have tried this:
#UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext)
var url = '#url.Action("index", "home")';
It does at the first Razor code with:
"The name 'UrlHelper' does not exist in the current context"
I can probably figure this part out (I have tried it with the full namespace as well). My main question is if this is still the right way to do things in Core. It seemed it might not be so which is when I stopped and asked here. I thought I was missing something.
I am programming a web application in C# MVC which dynamically loads information from a server in order to improve the speed.
Currently I have some errors and I am unable to diagnose why these are causing issues so I'll try my best to explain what's happening:
This div is created many times and grabs the ID for each project.
<div>
Open:
#{string JiraKey = item.JiraProjectKey;}
<span id="JiraOpen" onload="GetOpenJira"></span>
</div>
Then in the span, the script GetOpenJira is initiated:
<script id="GetOpenJira">
var url = "/HicVault/Projects/GetNumJiraOpenByKey";
var key = $('#JiraKey').val();
$.get(url, { input: key }, function (data) { $("#JiraOpen").html(data) });
</script>
This script SHOULD asynconously ask the controller to complete the function GetNumJiraOpenByKey with the JiraKey being used as a parameter. The function in the controller is:
[HttpGet]
public ActionResult GetNumJiraOpenByKey(string JiraProjectKey)
{
var sJql = "project = \"" + JiraProjectKey + "\" and status = \"Open\"";
var resultFieldNames = new List<string> { "resolution" };
Issues issues = new JiraClient(new JiraAccount()).GetIssuesByJql(sJql, 0, 1000, resultFieldNames);
return PartialView(issues.total);
}
Essentially this function returns an int once it has counted all of the issues for that particular project. I would like this to be done with AJAX using jQuery to load these values after the page has been loaded to vastly increase speed. (Currently without AJAX, pages take >30 sec to load).
Thanks if anyone can help.
EDIT: I suppose I should ask a question, currently with this code the page loads and after around 5 seconds, a server 500 error appears in the console stating there is an Internal Server Error. I know this is a general error, going in deeper points to the line:
"$.get(url, { input: key }, function (data) { $("#JiraOpen").html(data) ".
I am guessing either the logic of my work isn't possible in Razor MVC + JS, or I am getting the fundamentals of jQuery ajax get wrong?
rewrite your script as following...
<script id="GetOpenJira">
var url = "/HicVault/Projects/GetNumJiraOpenByKey";
var key = $('#JiraKey').val();
$.get(url, { JiraProjectKey: key }, function (data) { $("#JiraOpen").html(data) });
</script>
I have Durandal SPA which uses url.config.js file among different views. Bunch of urls to services are stored there.
Code for clarity:
define([], function () {
var serviceBaseUrl = 'http://localhost/Service/api/';
var portalPortalUrl = 'http://localhost/Portal';
});
And whenever I need to deploy my app, or run it with different IIS settings, I need to manually change this urls in code.
What I want:
To store them in Web.config file so I can have different configuration for debug and release modes.
I am using MVC 5 Razor views only for rendering bundles and initial content, all client side logic placed in Durandal folder.
I have only found solutions using ASP.NET ConfigurationManager like so:
function ReadConfigurationSettings()
{
var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
alert(k);
}
Or, for Razor:
#System.Configuration.ConfigurationManager.AppSettings["myKey"]
It's cool, but not my way.
Maybe it's possible to auto generate my urls.config.js file based on Web.config keys?
Thank you in advance.
If needed, here is my project structure:
- App //Durandal SPA
- Controllers
- Views //Only render initial view
- Web.config
You can use JavaScriptResult
Sends JavaScript content to the response.
Code, Controller Action method
public JavaScriptResult Config()
{
var script = string.Format(#"var configServiceBaseUrl = {0};", ConfigurationManager.AppSettings["var1"]);
return JavaScript(script);
}
In the page header(I would load the file first), You can define:
<script type="text/javascript" src='#Url.Action("Config", "Controller")'></script>
Now configServiceBaseUrl is Global JavaScript variable which you can use anywhere.
So you can use configServiceBaseUrl in url.config.js like
define([], function () {
var serviceBaseUrl = configServiceBaseUrl;
});
Adding to satpal, for SPA application such as angular js
For SPA's, such as angular you can use below code in your index.html as
<script type="text/javascript" src='/Controller/config'></script>
I have an ASP.NET MVC3 application published to a url like this:
http://servername.com/Applications/ApplicationName/
In my code, I am using jquery ajax requests like this:
$.get(('a/b/c'), function (data) {}, "json");
When I run the application locally, the ajax request goes directly to the correct page (being an mvc route) because the local page ends with a "/" (localhost/a/b/c).
However, when I publish to http://servername.com/Applications/ApplicationName/, the trailing "/" is not always present. The url could be http://servername.com/Applications/ApplicationName, which then causes the ajax request to try to load http://servername.com/Applications/ApplicationNamea/b/c, which fails for obvious reasons.
I have already looked into rewriting the url to append a trailing slash, but A) It didn't work, and B) I feel like it's a poor solution to the problem, and that it would be better to configure the javascript urls to work properly regardless of the local folder setup.
I did try "../a/b/c" and "/a/b/c", but neither seemed to work.
Thanks in advance for the help!
Personally I tend to use a global variable of the relative URL of the server in my view like:
var BASE_URL = '#Url.Content("~/")';
Then you can do things like :
$.get(BASE_URL + 'a/b/c'), function (data) {}, "json");
I would like to add that if you want it to be totally global, you could add it to your /Views/Shared/_Layout.cshtml instead.
I ran into the same problem, and ended up creating two JavaScript functions that mirror the functionality of the MVC Url helper methods Url.Action and Url.Content. The functions are defined in the _Layout.cshtml file, so are available on all views, and work regardless of whether the application is in the root of the localhost or in a subfolder of a server.
<script type="text/javascript">
function UrlAction(action, controller) {
var url = ('#Url.Action("--Action--","--Controller--")').replace("--Action--", action).replace("--Controller--", controller);
return url;
}
function UrlContent(url) {
var path = "#Url.Content("~/--file--")";
path = path.replace("--file--", url.replace('~/', ''));
return path;
}
</script>
These can then be called like so:
var url = UrlAction('AvailableAssetClasses', 'Assessment');
var url2 = UrlContent('~/Images/calendar.gif');
Always use Url helpers when generating urls in an ASP.NET MVC application and never hardcode them. So if this script is directly inside the view:
<script type="text/javascript">
var url = '#Url.Action("a", "b")';
$.get(url, function (data) {}, "json");
</script>
And if this script is inside a separate javascript file (as it should be) where you don't have access to server side helpers, you could simply put the url in some related DOM element. For example using HTML5 data-* attributes:
<div data-url="#Url.Action("a", "b")" id="foo">Click me</div>
and then in your javascript file:
$('#foo').click(function() {
var url = $(this).data('url');
$.get(url, function (data) {}, "json");
});
and if you are unobtrusively AJAXifying an anchor or a form, well, you already have the url:
$('a#someAnchor').click(function() {
var url = this.href;
$.get(url, function (data) {}, "json");
return false;
});