Rectangle 27 1

What I normally do is what @SimonRyan suggested, except I use an options object instead of passing just one string. Chances are if you need one, you will need another soon. So with an options object you have to modify less then when adding more parameters.

So the Initalise call would look like this:

Initialise({
    autoCompleteHelperUrl: '@(Url.Action("AutocompleteHelper"))',
    anAdditionalUrl: '@(Url.Action("AdditonalUrl"))'
})

asp.net mvc - Can I use Razor syntax inside Javascript included in a S...

javascript asp.net-mvc asp.net-mvc-4 razor scriptbundle
Rectangle 27 3

It's still the quotes. Json.Encode is providing double quotes, so you need to enclose your data-bind in singles:

<a data-bind='click: saveAboutMe(@Html.Raw(Json.Encode(User.Identity.Name)))'>save</a>

Could you possibly view source/inspect the element and post the outputted HTML rendered to the browser?

Output is: <a data-bind="click: saveAboutMe('" testuser"')"="">save</a>

Json.Encode

Notice I'm using a single quote wrapping data-bind rather than double-quote.

asp.net mvc - Pass MVC / Razor object to javascript / knockout? - Stac...

asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor knockout.js
Rectangle 27 10

You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d

jQuery post is the short version of jQuery ajax.

function addToCart(id)
{
  $.post('@Url.Action("Add","Cart")',{id:id } function(data) {
    //do whatever with the result.
  });
}

If you want more options like success callbacks and error handling, use jQuery ajax,

function addToCart(id)
{
  $.ajax({
  url: '@Url.Action("Add","Cart")',
  data: { id: id },
  success: function(data){
    //call is successfully completed and we got result in data
  },
  error:function (xhr, ajaxOptions, thrownError){
                  //some errror, some show err msg to user and log the error  
                  alert(xhr.responseText);

                }    
  });
}

When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.

This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.

Calling ASP.NET MVC Action Methods from JavaScript - Stack Overflow

javascript asp.net-mvc asp.net-mvc-3 razor
Rectangle 27 3

Use @Html.Raw to treat the string as raw HTML (e.g MVC will not encode it)

<script type="text/javascript">
   RunMap(@Html.Raw(Model.A), @Html.Raw(Model.B));
</script>

Of course, you need to make sure that the input (e.g the data) it handled carefully.

asp.net mvc - Pass a string from the controller to a partial view as j...

javascript asp.net-mvc razor
Rectangle 27 4

Basically, you can do it calling an AJAX POST:

$('form').on('submit', function (event) {
    // Stop the default submission
    event.preventDefault();

    // Serialize (JSON) the form's contents and post it to your action
    $.post('YourAction', $(this).serialize(), function (data) {
        // If you want to do something after the post
    });
});
public ActionResult YourAction(string JSONmodel)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

    MyModel model = serializer.Deserialize(JSONmodel, typeof(MyModel));

    // Now you can do whatever you want with your model
}

For more complex objects, you can use a third part solution for serialization/deserialization. It's well documented and broaden used:

Why not use the default model binder?

Maybe the OP wants to submit something in a different way, to a different Action. Who knows?

I needed something similar when using the jQuery jqGrid, as an example. I couldn't rely on the default model binder to achieve the result expected.

asp.net mvc - MVC4 passing all form data (model) from javascript to co...

javascript asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor
Rectangle 27 2

Razor code (@Url.Action(...)) runs server-side, while JavaScript runs client-side, long after the server has already done it's work, returned a response, and moved on to other things. As a result, you can't pass a JavaScript variable into a Razor method, as that JavaScript variable doesn't even exist as a thing yet.

If you need to include the value as part of the actual URL path, then you can perhaps construct the path manually. For example:

'<a href="@Url.Action("Detail", "Product")'+ obj.PRODUCT_ID + '">' + obj.PRODUCT_NAME + '</a>'

In other words, server-side, @Url.Action("Detail", "Product") is evaluated an returns something like /product/detail/. Then, client-side, in your JavaScript, all you're doing is just concatenating the product id onto this existing string, resulting in something like /product/detail/xxxxxx.

His razor code isn't even running. That call to @Url.Action is getting passed straight down to the client as is. I have asked him for his controller and full view code. I'm not sure he knows what that is or if that exists. I think he's treating it like just another js file.

/product/detail/xxxx
'<td><a href="@Url.Action("Detail", "Product")/' + obj.PRODUCT_ID + '">' + obj.PRODUCT_NAME + '</a></td>' +

asp.net mvc - How to format action link pass parameter in mvc? - Stack...

asp.net-mvc html.actionlink url.action
Rectangle 27 1

I got something like {Cities:[{&q....64635201372,Cities:0}}) in the result

How are you creating the JSON string? Maybe you can use JsonValueProviderFactory and declare your props as Json. Here's a related article: haacked.com/archive/2010/04/15/

I used a StringBuilder and create my own (since I need to add on some logics and please see my ViewClass). How can I correctly declare the return type to avoid this problem?

asp.net mvc - Pass a string from the controller to a partial view as j...

javascript asp.net-mvc razor
Rectangle 27 2

The first code sample is missing a pair of single or double quotes. The second one is ok. It works for me.

Or what do you mean by "This has no effect."? Have you looked at the generated HTML code? What do you get?

asp.net mvc 3 - How do i include mvc3 razor variable in javascript? - ...

javascript asp.net-mvc-3 include razor
Rectangle 27 1

Yes it is possible in a simpler way.

  • Alternate of example provided by MelanciUK. $('form').on('submit', function (event) { // Stop the default submission event.preventDefault(); // User same property name as in Model $.post('YourAction', {prop1 : 'a', prop2 : 'b'}, function (data) { // If you want to do something after the post }); }); [HttpPost] public ActionResult SampleAction(SampleModel sModel) { }

You can achieve the same thing by stadard MVC(ModelBinding) convention i.e. no need to serialize and deserialize.

I haven't personally verified the above, but it looks very helpful. If anyone wants to try it, please post whether it actually works or not.

asp.net mvc - MVC4 passing all form data (model) from javascript to co...

javascript asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor
Rectangle 27 0

MVC 3 isn't dependant on JavaScript or vice-versa.

Resources for learning to use javascript with asp.net-mvc 3 and cshtml...

javascript asp.net-mvc-3 razor
Rectangle 27 0

Basically, you can do it calling an AJAX POST:

$('form').on('submit', function (event) {
    // Stop the default submission
    event.preventDefault();

    // Serialize (JSON) the form's contents and post it to your action
    $.post('YourAction', $(this).serialize(), function (data) {
        // If you want to do something after the post
    });
});
public ActionResult YourAction(string JSONmodel)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

    MyModel model = serializer.Deserialize(JSONmodel, typeof(MyModel));

    // Now you can do whatever you want with your model
}

For more complex objects, you can use a third part solution for serialization/deserialization. It's well documented and broaden used:

Why not use the default model binder?

Maybe the OP wants to submit something in a different way, to a different Action. Who knows?

I needed something similar when using the jQuery jqGrid, as an example. I couldn't rely on the default model binder to achieve the result expected.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

asp.net mvc - MVC4 passing all form data (model) from javascript to co...

javascript asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor
Rectangle 27 0

In a javascript console, try the following:

"0" == false

Helpful, eh? I suspect MVC Is playing silly beggars, assuming that's what you meant. First, try inspecting the POST request in the net panel of Firebug (or whatever web debugging you use), then I'd suggest you try using plain numbers instead of strings.

javascript - Pass list of string into Controller in mvc 3 Razor - Stac...

javascript jquery .net asp.net-mvc-3 razor
Rectangle 27 0

I believe this could be done only after the HTML is rendered. The reason behind this is the Razor is mainly used for rendering the HTML. The Javascript could be run upon for a HTML element only its is completely rendered. If I understood your question, you want to dynamically assign the URL which is rendered by the javascript function to the data_autocomplete property of the textbox. I would suggest you the method below

var currentURL = @Url.Action("SomeAction","SomeController");

var parameters  = YourJSMethodToreturnTheParameterValue();

$("#SomeProperty").attr("data_autocomplete",currentURL+'?someParameter='+parameters;

Ideally, the TextBoxFor would render the Property name as its ID.

Well, thanks for the reply. I did it but it seems the js added parameter isn't passed to the action. It is null when I break point it!

One point: Just ensure if the action has the parameter with same name and query string param? Can you please post your sample script and the action method ?

asp.net - How to access the string output of a JavaScript function in ...

javascript asp.net asp.net-mvc razor url-action
Rectangle 27 0

A 4th option is to return a razor view with the ContentType set to text/javascript as the response. Razor will render the partial views, but then the browser will execute the javascript to update the DOM.

You'll have to make sure your ajax call is done correctly so that it executes the response.

$("#Categories").html('@Html.RenderPartial("_Categories", Model.Categories)')
$("#Divisions").html('@Html.RenderPartial("_Divisions", Model.Divisions)')
$("#Products").html('@Html.RednerPartial("_Products", Model.Products)')

Thanks for the response! However, this will still require that I wait for the initial ajax call to return before making the other 3 ajax calls.. is that a bad practice? Is there a problem with my design that is making this a difficult problem?

When the user changes the category, make an ajax request to fetch the divisions for that category. On the server side, store not only the divisions in the ViewModel, but also the products for the first division. Your controller action then returns the view as described in the answer. In your view code you will write the js above. Asp.net MVC will replace the string in the .html() with the actual html response from each partial. Only then will that response be sent to the client. The client is basically getting executable js code and your respective sections are filled in one ajax call.

@ntsue, you may have already figured out on your own, what I just said. However, I wanted to say it out loud, so in case there is anything wrong with my understanding of it, BZink can correct me ... :)

@Amith George, Thanks!! I actually did misread the proposed solution.

asp.net mvc 3 - Returning multiple partial views on single AJAX call -...

ajax asp.net-mvc-3 partial-views
Rectangle 27 0

It has too, or the javascript will break since you have the name in single quotes.

title: '@s.Name'

now if s.Name has a single quote in it then this line will become something like

title: 'this won't work'

which is not valid javascript

My guess is that the razor engine is smart enough to know this, and thus encodes the single quote in the name for you so your js doesn't break.

title: "@s.Name"

and see if it works better for you :)

Remember that in javascript a string can be both be in single and double quotes.

I know that javascript's string can contain single and double quotes. But solution you suggested didn't work :(

jquery - Javascript, Razor and Escape characters. Like apostrophe - St...

javascript jquery jquery-plugins asp.net-mvc-3 razor
Rectangle 27 0

I originally solved this problem by moving the AJAX call to a separate function and passing in the values needed as variables. However, as I recently found out, one can access the razor view code in Javascript by simply surrounding it in quotes. I feel a bit silly, but hey, learning.

jquery - Access index of model data member in javascript - Stack Overf...

jquery asp.net-mvc razor
Rectangle 27 0

If you want to share static resources such as images, stylesheets and javascript files between multiple projects I would recommend you creating a separate web application that will host those resources and which will be accessed by all other applications. A sort of CDN if you will. The benefit of a CDN is that all applications have a single location for those static resources meaning that clients of all applications will have those resources in cache.

If you want to store them in a separate assembly that would mean that each application will have a different copy of them => clients of your applications won't benefit from this caching. You could still do it if you will. Simply embed those resources into the library and then write a controller action that will read them and serve them.

How do I access an embedded resource from a controller?

razor - asp.net mvc 3: store stylesheets, images and javascript in sha...

asp.net-mvc-3 razor
Rectangle 27 0

You cannot pass a value from javascript to a method run in Razor, because the razor code is run on the server before the page is rendered, and javascript code is run on the client. This means you can't directly pass the javascript value to the razor method, but to accomplish what you want, you can build the link without the parameter in razor, then append it in javascript when you need to:

The razor code is run before the page is rendered, so you'll get something like this if you view source (rendered page):

$('#btnAdmDel').click(function () {
    $.get('http://example.com/SuperUser/deleteAdm' + '?id=' + $('#tbSeek').val(), function (data) {
        $('#partials').html(data);
    });
});

And then when the click event is fired, it appends ?id= and the value to the url to get. It's critical that you understand the execution time of both Razor and JavaScript code.

I understood the concept of the different execution times between them. You're saying that the Razor code is run when I "compile" the project, and the javascript code is run when the page loads in the browser. The source code is exactly like you said in the browser, but the action method is not being executed.

@guilofrano No, the razor code is not run when you compile the project. It's executed at run time when the view is rendered. If this isn't working, you've got some other issue. Is the deleteAdm method marked with an HttpPost Attribute? If so, you won't be able to hit it with a GET request.

It's actually not marked at all. I tried marking it with [HttpGet], but it didn't work

asp.net mvc - Passing cshtml field value to url.action through jquery ...

jquery asp.net-mvc
Rectangle 27 0

var textbox = document.getElementById('SomeProperty');
var currentUrl = textbox.getAttribute('data_autocomplete');
currentUrl  += '?someParameter=' + myJsFunctionThatReturnsString();
textbox.setAttribute('data_autocomplete', currentUrl);

asp.net - How to access the string output of a JavaScript function in ...

javascript asp.net asp.net-mvc razor url-action
Rectangle 27 0

You could do that for ASP.NET MVC4 Razor this way:

@{
    var apiBaseUrl = ConfigurationManager.AppSettings.Get("ApiBaseUrl");
}

<script type="text/javascript">
    $(document).ready(function() {

      var request = $.ajax({
          url: '@apiBaseUrl/cases',
          type: 'GET',
          cache: false,
          dataType: 'json'
      });

    });
</script>

How to update JavaScript with a value from web.config file in an ASP.N...

javascript asp.net asp.net-mvc