Conditional Compilation is Turned Off VS 2012 razor javascript - c#

I have searched SO and not found a solution to this problem. I have code like this:
<script>
$("AddToFavorites").Click(function() {
var apiLink = "/url/AddToFavorites?id=" + #Model.RecipeId;
$.ajax({
url: apiLink,
type: "GET"
});
});
</script>
the . in Model.RecipeId gets underlined and I get a compiler error of:
Conditional compilation is turned off
Is it not possible to use c# code in a javscript block? If this is the case, how do I get around it to make the url dynamic in a case like this?
Thanks.

Try changing the code to
<script type="text/javascript">
$("AddToFavorites").click(function() {
var apiLink = "/url/AddToFavorites?id=" + "#(Model.MerchantID)";
$.ajax({
url: apiLink,
type: "GET"
});
});
</script>
also you may want to add
/*#cc_on #*/
if the error continues to happen.

Related

absolute path on call ajax mvc4 c#

i have a project in mvc 4 entity framework and call the controller method with ajax.
My problem is when i am using my app local, url is "Controller/Method" but when i publish i have to change url to "http://domain/appName/Controller/Method"
who can i do to get absolute path on ajax url??? my ajax is on js file and i can't use function like html.actionlink
example:
$("#btnAnswer").click(function () {
$.ajax({
url: "http://domain/appName/Controller/method/",
//url: "/Controller/method/",
data: { answer: $("#answer").val(), question_id: $("#question_id").val(), answer_id: $("#answer_id").val() },
success: function (result) {
alert(result);
}
}).error(function () {
}).fail(function () {
});
});
You don't really need the absolute url. Correct relative url is fine.
You should use the Url.Action helper method to generate the correct relative path to your action method. This will generated the proper path irrespective of your current page/view.
url: "#Url.Action("ActionMethodName","YourControllerName")"
Url.Action helper method will work if your javascript code is inside a razor view. But if your code is inside an external js file, you should build the relative url to your app root using Url.Content("~") helper method and pass that to your js code via a variable as explained in this post . Try to use javascript namespacing when doing so to prevent possible conflict/overwriting from other global variables with same name.
EDIT : Including Marko's comment as an alternate solution. Thank you :)
If it is an anchor tag, you can simply use the href attribute value of the clicked link.
Delete
and in your js code
$("a.ajaxLink").click(function(e){
e.preventDefault();
var url = $(this).attr("href");
//use url variable value for the ajax call now.
});
If it is any other type of html element, you can use html5 data attribute to keep the target url and use the jQuery data method to retrieve it in your js code.
<div data-url="#Url.Action("Delete","Product")" class="ajaxLink">Delete</div>
and in your js code
$(".ajaxLink").click(function(e){
e.preventDefault(); // to be safe
var url = $(this).data("url");
//use url variable value for the ajax call now.
});
As you are using this in a js file you can do something like this:
$("#btnAnswer").click(function () {
var hostString = window.location.protocol + "//" + window.location.host + /";
$.ajax({
url: hostString + "/appName/Controller/method/",
//url: "/Controller/method/",
data: { answer: $("#answer").val(), question_id: $("#question_id").val(), answer_id: $("#answer_id").val() },
success: function (result) {
alert(result);
}
}).error(function () {
}).fail(function () {
});
});

Open jQuery UI Dialog from Code Behind

I am kind of new with jQuery and JavaScript, and I ran into a problem.
I am having some problems to open the jQuery UI Dialog Box from my ButtonField within the Gridview:
<asp:ButtonField ButtonType="link" Text="Modify Deadline" Visible="true" runat="server" CommandName="modifyDeadline" ControlStyle-CssClass="button" ItemStyle-CssClass="sliderPopupOpener"/>
At first I tried to give a class to the above and named it sliderPopupOpener, and make it open the jQuery Popup when clicked as below:
$(".sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
However, this was not working because of the postback, apart from that, it also does not work with my approach. Since I would like to get some data from the database before showing the jQuery UI Dialog. So I think the best approach is to call the Dialog function from the Code Behind.
How can I do this?
I tried this approach, but it did not work, I am not sure if I am doing something wrong.
if (e.CommandName == "modifyDeadline")
{
string sliderPopupFunction = #" <script type=""text/javascript"">
$(function () {
jQuery(function () {
$(""#sliderPopup"").dialog(""open"");
}
});
</script>";
ClientScript.RegisterStartupScript(typeof(Page), "key", sliderPopupFunction);
}
Is the above possible? If so, what am I doing wrong?
EDIT:
I noticed everyone is giving their answers with a way around this, rather than telling me whether this is possible just by calling the jQuery function from the Code Behind. Although I appreciate other solutions, I would appreciate if I could get this to work, with the least effort possible, through the code behind, since I have everything ready that way.
Instead of directly bind the click event handler, you should try delegated events using live (deprecated since jquery 1.7) or on.
That way, you should change this :
$(".sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
Into something like this :
$(body).on("click", ".sliderPopupOpener", function(){
$("#sliderPopup").dialog("open");
});
alternative
If the code-behind approach is more suitable for you, you should try calling the method directly in your script, i.e, change this :
string sliderPopupFunction = #" <script type=""text/javascript"">
$(function () {
jQuery(function () {
$(""#sliderPopup"").dialog(""open"");
}
});
</script>";
into simply this :
string sliderPopupFunction = #" <script type=""text/javascript"">
$(""#sliderPopup"").dialog(""open"");
</script>";
Also, if your sliderPopup is a server-side control, you should replace the #sliderPopup with the client Id generated by ASP .NET (using sliderPopup.ClientID).
Another thing to consider is if your sliderPopup located inside the update panel, you should try re-initialize the Jquery UI dialog first, something like this :
$("#sliderPopup").dialog().dialog("open");
Just Replace the <asp:ButtonField with <asp:TemplateField the write whatever you want:
<asp:TemplateField>
<ItemTemplate>
<input type="button" onclick='jsFunctionThatShowsTheDialog()'/>
</ItemTemplate>
</asp:TemplateField>
I think in this situation it would be better for you to use a plain old <input type="button/> button and use ajax to perform your call to the server, and then with the returned data append it to your html and use the dialog. Ajax will perform your code behind without posting back your entire page.
EDIT: here is an example I did a while ago
//declaring the web method annotation allows this method to be accessed by ajax calls
//scriptmethod tells this method to take the data that we're returning, and encode it as a json so we can use it in javascript
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Person> getPeople() {
List<Person> people = null;
using (testDataEntities context = new testDataEntities()) {
people = context.People.ToList();
}
return people;
}
$(document).ready(function () {
$("#getPeople").click(function () {
$.ajax({
type: "POST",
data: {},
url: "Default.aspx/getPeople", //getPeople is the name of the method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = msg.d;
var $table = $("<table></table>");
$.each(data,function(){
$table.append("<tr><td>"+this.MyProperty+"</td></tr>")
});
$table.dialog();
}
});
});
});

Getting link to an action?

I have an action in a MobileController called 'myaction' and I call it with javascript like so:
<script type="text/javascript">
function SubmitData() {
$.ajax(
{
type: "POST",
url: "http://localhost:1613/Mobile/myaction",
data: "id to post",
success:
function (result) {
window.alert("SUCCESS");
},
error: function (req, status, error) {
window.alert("ERROR!");
}
}
);
}
</script>
Notice however the url is not using relative paths, I tried making it just ~/Mobile/myaction but that didn't work.
Any ideas how I can make it so the url being pointed to will work in all cases and not just if the domain is localhost:1613? Like if I uploaded it to mysite.com it would find the action at mysite.com/mobile/myaction.
Thanks for any help!
Have you tried:
url: "#Url.Action(....)",
Replace the url by:
url: "/Mobile/myaction"
With ~ sign, it will only work with server controls/functions.
url: "#Url.Content("~/appName/Mobile/myaction/")"
Html::"/appName/Mobile/myaction/"I suggest you to give your app Virtual path "/appName" doing this i'll allow you to avoid appName in url
You can use something like this:
new UrlHelper( HttpContext.Current.Request.RequestContext ).Action( "<action>", "<controller>", new { id = 1 } )
I'm using this exactly to pass values to a javascript function

Mix Razor and Javascript code

I'm pretty confused with how to mix razor and js. This is the current function I am stuck with:
<script type="text/javascript">
var data = [];
#foreach (var r in Model.rows)
{
data.push([ #r.UnixTime * 1000, #r.Value ]);
}
If I could declare c# code with <c#></c#> and everything else was JS code -- this would be what I am after:
<script type="text/javascript">
var data = [];
<c#>#foreach (var r in Model.rows) {</c#>
data.push([ <c#>#r.UnixTime</c#> * 1000, <c#>#r.Value</c#> ]);
<c#>}</c#>
What is the best method to achieve this?
Use <text>:
<script type="text/javascript">
var data = [];
#foreach (var r in Model.rows)
{
<text>
data.push([ #r.UnixTime * 1000, #r.Value ]);
</text>
}
</script>
Inside a code block (eg, #foreach), you need to mark the markup (or, in this case, Javascript) with #: or the <text> tag.
Inside the markup contexts, you need to surround code with code blocks (#{ ... } or #if, ...)
you also can simply use
<script type="text/javascript">
var data = [];
#foreach (var r in Model.rows)
{
#:data.push([ #r.UnixTime * 1000, #r.Value ]);
}
</script>
note #:
Never ever mix more languages.
<script type="text/javascript">
var data = #Json.Encode(Model); // !!!! export data !!!!
for(var prop in data){
console.log( prop + " "+ data[prop]);
}
In case of problem you can also try
#Html.Raw(Json.Encode(Model));
A non conventional method to separate javascript from the view, but still use razor in it is to make a Scripts.cshtml file and place your mixed javascript/razor there.
Index.cshtml
<div id="Result">
</div>
<button id="btnLoad">Click me</button>
#section scripts
{
#Html.Partial("Scripts")
}
Scripts.cshtml
<script type="text/javascript">
var url = "#Url.Action("Index", "Home")";
$(document).ready(function() {
$("#btnLoad").click(function() {
$.ajax({
type: "POST",
url: url ,
data: {someParameter: "some value"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg.d);
}
});
});
});
</script>
This is my way to hack Razor and use Javascript without freaking out Intellisense.
Obviously you should use <text> but with an "expedient": double braces before.
This is what happens if a single brace is used:
This is what happen if a couple of braces are used:
Now constants and variable have been recognized.
It's better, but not good!
There is still the "less than" symbol that confuses intellisense making it think that following is the name of a tag. The "less than" sign is signaled as error and from here there are parsing errors as "console.log" shows.
You need to add something that quiets intellisense and doesn't get returned in the final JS code at compile time.
Solution: use this comment after "less than": /*>*/
This is the result
It's quite strange to see, but it works as it should.
you can use the <text> tag for both cshtml code with javascript
Wrap your Razor code in #{ } when inside JS script and be aware of using just #
Sometimes it doesn't work:
function hideSurveyReminder() {
#Session["_isSurveyPassed"] = true;
}
This will produce
function hideSurveyReminder() {
False = true;
}
in browser =(

Problem with jQuery selector and MasterPage

I have a problem with a master page containing a asp:textbox that I'm trying to access using jQuery. I have read lot sof thread regarding this and tried all the different approaches I have seen, but regardless, the end result end up as Undefined.
This is the relevant part of the MasterPage code:
<p><asp:Label ID="Label1" AssociatedControlID="osxinputfrom" runat="server">Navn</asp:Label><asp:TextBox CssClass="osxinputform" ID="osxinputfrom" runat="server"></asp:TextBox></p>
When I click the button, the following code from a jQuery .js file is run:
show: function(d) {
$('#osx-modal-content .osxsubmitbutton').click(function (e) {
e.preventDefault();
if (OSX.validate()){
$('#osx-modal-data').fadeOut(200);
d.container.animate(
{height:80},
500,
function () {
$('#osx-modal-data').html("<h2>Sender...</h2>").fadeIn(250, function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'from':'" + $("#osxinputfrom").val() + "','mailaddress':'" + $("#osxinputmail").val() + "','header':'Test3','message':'Test4'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Meldingen er sendt!</h2>');
$('#osx-modal-data').fadeIn(200);
});
},
error: function(msg){
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Feil oppstod ved sending av melding!</h2>');
$('#osx-modal-data').fadeIn(200);
});
}
});
});
}
);
}
else{
$('#osxinputstatus').fadeOut(250, function () {
$('#osxinputstatus').html('<p id="osxinputstatus">' + OSX.message + '</a>');
$('#osxinputstatus').fadeIn(250);
});
}
});
},
So the problem here is that $("#osxinputfrom").val() evaluated to Undefined. I understand that the masterpage will add some prefix to the ID, so I tried using the ID from the page when it's run that ends up as ct100_osxinputfrom, and I also tried some other hinds that I found while searching like $("#<%=osxinputfrom.ClientID%>"), but it ends up as Undefined in the method that is called from the jQuery ajax method anyway. The third and fourth parameters to the ajay function that is hardcoded as Test3 and Test4 comes fine in the C# backend method.
So my question is simply: How can I rewrite the jQuery selector to fetch the correct value from the textbox? (before I used master pages it worked fine by the way)
Best regards
Daemon
It will be abit slower but why dont you try adding cssclass="bla" to your label and then get it with $('.bla').val(); ?
You should use the attribute ends with selector
Link
it would be $("id$='osxinputfrom'")

Categories

Resources