How do I pass a javascript parameter to an asp.net MVCmodel from within a View?

Posted by Josh on Stack Overflow See other posts from Stack Overflow or by Josh
Published on 2010-03-28T23:34:03Z Indexed on 2010/03/28 23:43 UTC
Read the original article Hit count: 152

Filed under:
|
|
|
|

Hi everyone!

I am having an issue trying to access a list property on a model from within a javascript. My basic situation is this:

  • I have an ArticleController and an ArticleViewModel. An Article has a number of properties, one of which is Text, which is just a string that contains the contents of the article. The ArticleViewModel contains a Pages property, which is just a List of Strings. When the ArticleViewModel constructor is called, I populate the Pages list by dividing up the article text based on some delimeters.

  • I have a View which inherits the ArticleViewModel type. What I want to do is only display one page at a time, and then when the user clicks a page number (from a list at the bottom of the article), I want to use javascript to load that page into the #dynamicContent div.

  • The problem: I can't seem to pass a parameter to the Model.Pages property from within javascript... Is this possible? I get an error stating, "Expression Expected" when I try what I have below. I don't want to have to worry about AJAX calls or anything like that since I already have the entire article... I just need a way to access each individual page from within the javascript function.

  • Alternatively, if there is a better solution for "paginating" an article so that I can load each articlePage without having to refresh the entire html page, I would certainly be open to that as well.

Any help would be much appreciated!! Thanks for your time!

ArticleView Code:

Script at the top of the view:

   function loadPage(pageNumber) {
       try {

           alert(pageNumber);

           $('#dynamicContent').html('<%=Model.Pages(' + pageNumber + ') %>');

       }
       catch (e) {
           alert('in here');
           alert(e.description);
       }
   }

HTML for view: [...]

<div id="articleBody">
    <div id="dynamicContent">
         <%=Model.Pages(0)%>
    </div>
  </div>
  [...]

Page Links at bottom of page: [...]

 <div> 
      <ul style="display:block">        
         <li style="display:inline"> 
            <a href="#articleTitle" onclick="loadPage(0)"> 1 </a> 
         </li> 
         <li style="display:inline"> 
            <a href="#articleTitle" onclick="loadPage(1)"> 2 </a> 
         </li>    
      </ul>
  </div>  

© Stack Overflow or respective owner

Related posts about mvc

Related posts about ASP.NET