Accessing ASP.NET MVC Model Data from external Javascript file

MegaMatt picture MegaMatt · Nov 14, 2009 · Viewed 7.4k times · Source

I'm trying to use JQuery's $.getJSON to access Model data from the Controller, and build a JSON object in the javascript to use as the user adds and removes items from a list. All JS is done in an external file. The hit to the server for the Model data is done only once after the page first loads so I can get the full list of options for the user to choose from. After that, the user can modify the list as much as he wants (and the JSON object is updated accordingly), and then save it off (gets written back to the DB).

But here's my problem: When using $.getJSON, the method I need to call in the Controller needs an ID so that it can look up what particular resource I'm talking about and get back the list of options that pertains to that particular resource. But from an external JS file, I don't know how to get that ID to pass to the Controller. It's built into the link that opens the page in the first place, and is sitting in the URL, but once the page loads I don't know how to get this ID in order to pass it to the Controller. I've pasted some of my code below, because I know this is confusing:

Details method in Controller that initially loads a page (takes a resourceID to know what to load):

public ActionResult Details(string resId)
{
    //call base method
    base.Details(resId, resourceType);
    Evaluation eval = (Evaluation)this.Model;
    ViewData.Model = eval;
    return View("Index");
}

In my external JS file, I'm doing this:

$.getJSON("/Evaluation/PopulateJournalOptions/" + id, populateJSON);

And in the Controller, I wrote another method called PopulateJournalOptions that gets called to build the JSON object:

public JsonResult PopulateJournalOptions(string resId)
{
   JournalOptionsResult jsonResult = new JournalOptionsResult();

   base.Details(resId, resourceType);
   Evaluation eval = (Evaluation)this.Model;

   jsonResult.Activities = eval.Journal.Activities;
   jsonResult.Issues = eval.Journal.Issues;
   jsonResult.ScheduledActions = eval.Journal.ScheduledActions;

   return Json(jsonResult);
}

Again, my problem is that, once the page loads, I don't have access to the ID I need to pass to PopulateJournalOptions. I've tried just not passing anything to PopulateJournalOptions, and creating a new object there and setting it equal to (Evaluation)this.Model, but this.Model appears to be null, probably because it's a new instance of the Controller once it's called from the JS. So I'm kind of stuck here. Any ideas?

Answer

tvanfosson picture tvanfosson · Nov 15, 2009

Have you thought about putting the id into a hidden field on the page and then having your javascript read the id from the field?

$.getJSON("/Evaluation/PopulateJournalOptions/" + $('#Id').attr('value'), populateJSON);

Then, in your view,

<%= Html.Hidden("Id") %>

With your model having the required Id as a property