Happy Halloween everyone, hope it was a fun night!
I've just implemented an AJAX search functionality on my first ever ASP.NET MVC project, and I just want to get your feedback on security and performance.
The project is going to be a simple Forum, with roughly 40 topics and 1000-3000 total posts.
Let me show you some code.
In my TopicsController.cs
file, I've created a JsonResult
action that looks like this:
public JsonResult Search(int id, string title, string keyword)
{
var searchResults = from p in topicRepository.SearchPosts(id, keyword, 10)
select new
{
Title = p.Title,
ReplyCount = p.ReplyCount,
CreatedBy = p.CreatedBy,
LastUpdated = p.LastUpdatedFriendly,
Replies = p.ReplyCount,
Views = p.Views
};
return Json(searchResults, JsonRequestBehavior.AllowGet);
}
The topicRepository.SearchPosts()
is quite simple
public IQueryable<Post> SearchPosts(int topicId, string keyword, int limit)
{
var topics = from p in db.Posts
where p.TopicID == topicId && p.Title.StartsWith(keyword)
orderby p.Title ascending
select p;
return topics.Take(limit);
}
So basically, I generate a JSON object based on a topicId
and a keyword
that gets passed via the $.getJSON()
method.
$.getJSON(
url,
{ id: id, keyword: val },
function(json) {
console.dir(json);
}
);
The id
comes from an Url.Action method while keyword
is a string that gets it's value from an input box on the keyup()
event. I delay the request by about 300ms to make sure too many requests aren't sent to the server while the user is typing.
The JSON comes back successfully and I build my table appropriately with some nice animations etc.
Now, since this is my first ever ASP.NET MVC project I have obvious concerns about security and performance.
- Could the code be optimized for faster results?
- Should I use caching of some sort to improve the speed?
- By fiddling with the data sent to the server, could a malicious user do some damage?
- Should I be doing anything else differently?
I don't expect answers to all my questions but any help is highly appreciated.
Thanks in advance,
Marko