0

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.

As it stands I make an ajax call like this:

$.ajax({
    type: "POST",
    url: "/timetabler/Includes/ajaxModulesByUserId",
    data: { id: UserId  },
    success: function (data) {
        alert(data);
        if (data == "ERROR") {
            alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
        }
    }
});

This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.

Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:

public IEnumerable<dynamic> getAllQuery(string query)
    {
        return _db.Query(query);
    }

To execute my query.

Now I call it in my Razor code like this:

string input = "";
    input = Request["id"];
    var arr = new List<string>();
    if (!string.IsNullOrEmpty(input))
    {
        // Add new sheet to database
        using (var repo = new initDatabase("SQLServerConnectionString"))
        {
            foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
            {
                arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
            }
            @session.Serialize(arr);
        }
    }

So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.

As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:

public static string Serialize(object o)
    {            
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(o);
    }

This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:

Example Output

How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.

Would really appreciate it if you could help me get my output correct.

Thanks

1 Answer 1

0

The Web Pages framework includes a Json helper which can take your data and return it as JSON.

if (!Request["id"].IsEmpty())
{
    using (var repo = new initDatabase("SQLServerConnectionString"))
    {
        var data =  repo.getAllQuery("SELECT * FROM Module WHERE userID = @0", Request["id"])
        Json.Write(data, Response.Output);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.