Grey Walker
Grey Walker

Reputation: 125

Passing a value from javascript to Action Result

I am trying to pass a variable form javascript to an action result, I dont get any errors but I cant get it to work either.

I have the following javascript that when a user selects an item the item they select should be passed into the action result.

.on('select_node.jstree', function (e, data) {
//alert('You selected node: ' + data.node.text);
url.actionURL("/SinqLaison/UpdateItemData", data.node.text);
$.ajax({
    url: '@Url.Action("UpdateItemData", "SinqLaison")',
    type: 'POST',
    data: { query: data.node.text }
});

The action result I am trying to pass the query to is

public ActionResult UpdateItemData(string query)
    {
        List<MarketItem> items = new List<MarketItem>();

        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = connString;
        SqlCommand sqlCom = new SqlCommand("SELECT * FROM Items where Id =" + query , connection);
        connection.Open();
        SqlDataReader reader = sqlCom.ExecuteReader();
        while (reader.Read())
        {
            var item = new MarketItem()
            {
                id = Convert.ToInt32(reader["Id"]),
                name = reader["Name"].ToString(),
                marketParentGroup = Convert.ToInt32(reader["MarketGroup"] == DBNull.Value ? 0 : Convert.ToInt32(reader["MarketGroup"])),
                icon = reader["Icon"].ToString()
            };
            items.Add(item);
        }
        connection.Close();

        return View();

I get the following 404 error in the FireFox debugger. I'm sure the action and controller are correct. Is my javascript sysntax wrong?

enter image description here

Upvotes: 0

Views: 1411

Answers (1)

Shyju
Shyju

Reputation: 218722

From the screenshot, It looks like your code is placed inside an external javascript file. The @Url.Action helper method is a C# method, which needs to be placed in a file which the server executes. The view file is the place for this. the server cannot execute your C# method calls placed in a javascript file.

You need to execute the Url.Action method in the view and pass that to the external js file.

So in your view file, execute the Url.Action helper method and store that value (the relative url) to a javascript variable. You need to make sure you are doing this before loading the script which has your ajax call. Also make sure to use javascript namespacing to avoid overwriting of evil global variables.

<script>
    var myProj = myProj || {};
    myProj.urls = myProj.urls || {};
    myProj.urls.updateItemDataUrl='@Url.Action("UpdateItemData", "Home")';    
</script>
<script src="~/Scripts/MyExternalJsFileWhichHasAjaxCode.js"></script>

Now in your external javascript file, you can access it like

$.ajax({
    url: myProj.urls.updateItemDataUrl,
    type: 'POST',
    data: { query: 'myTest' }
});

Upvotes: 1

Related Questions