-1

I have the below c#.net code which works and returns me the url.I want to write equivalent code from javascript/jquery .

HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current);
Uri uri = httpContext.Request.Url;
string url = UrlHelper.GenerateContentUrl(imageSource, httpContext);

Is there any way I can write its equivalent code in the jquery/javascript or is there a way I can call this c# code from javascript if I have it in a method?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user3481630
  • 101
  • 10
  • possible duplicate of [Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view](http://stackoverflow.com/questions/5980389/proper-way-to-use-ajax-post-in-jquery-to-pass-model-from-strongly-typed-mvc3-vie) – Liam Jun 04 '14 at 08:37
  • That link is informative, but not helpful for my issue. – user3481630 Jun 04 '14 at 08:43

1 Answers1

1

You can't write a JavaScript/jQuery equivalent code for C# server side code.

All you can do is, render the server side string variable into a JavaScript variable of your view.

There are many ways to do. But you could make use of ViewBag in this case.

Using ViewBag

public ActionResult MyAction()
{
 HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current);
 Uri uri = httpContext.Request.Url;
 ViewBag.MyUrl= UrlHelper.GenerateContentUrl(imageSource, httpContext);
 return View();
}

then in a View

<script type="text/javascript">
var myUrl='@ViewBag.MyUrl';
</script>

Embed it in a view

@{

HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current);
Uri uri = httpContext.Request.Url;
String url = UrlHelper.GenerateContentUrl(imageSource, httpContext);
}

<script type="text/javascript">
var myUrl='@url';
</script>
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120