Skip to main content

Posts

Showing posts from 2013

Posting Data on a ViewModel with a Constructor with Parameters

If you ever get into a MVC ViewModel Error - No parameterless constructor defined for this object , then you got into a situation where you have a viewmodel that needs parameters. Example: namespace Application.Web.Models { public class GameweekViewModel { public virtual IEnumerable<Book> BookList { get; set; } public BookSheelViewModel(IStoreDataSource db) { this.BookList = db.Books.ToList(); } } } Once you post this model back to the controller, MVC will need to create a new instance and will not know how to. The easiest solution is to add a parameterless constructor to the Viewmodel: namespace Application.Web.Models { public class GameweekViewModel { public virtual IEnumerable<Book> BookList { get; set; } public BookSheelViewModel() {  } public BookSheelViewModel(IStoreDataSource db) { this.BookList = db.Books.ToList(); } } } Another Soluti

Templates in Javascript with jQuery

The jQuery template: <script id=" bookTemplate " type="text/x-jquery-tmpl">     <tr>         <td>${Author}</td>        <td>${Title}</td>         <td>${Subject}</td>     </tr> </script> Template being used: $('#authors').change(function () {         var author = $('#authors').val();         api.getBooksByAuthor({             success: function (result) {                 $('#bookTableBody').empty();                 $('# bookTemplate ') .tmpl( result ) .appendTo('# bookTableBody ');             }         }, author);     }); Example HTML code where the table cell content is applyed: <table width="600">     <thead>         <tr>             <th>Author</th>             <th>Title</th>             <th>Subject</th>         </tr>     </thead>     <tbody id=" bookTableBody ">    

Razor Helpers with ASP.NET MVC

Add a  App_Code  folder to your project and create a new  CustomHelpers.cshtml  file in it. Add you custum helpers to the file, such as: @helper Truncate(string input, int length) { if(input.Lenght <= Lenght) { @input } else { @input.Substring(0, length)<text>...</text> } } The in order to use it in your razor views, you can do something like: @CustomHelpers.Truncate(ViewBag.SomeMessage as string, 8)