Skip to main content

Posts

What is the purpose of accessors?

Can somebody help me understand the  get  &  set ?  Why are they needed? I can just make a public variable. What  are  properties? Properties are language elements that allow you to avoid the repetitive  getXYZ()  accessors and  setXYZ()  mutators techniques found in other languages, like Java. Why do they exist? They aim to solve the following problems: Saying  get  and  set  in the beginning of every access or mutation of a value is annoying and distracting. In Java, you often say: class person { private int _age ; public void setAge ( int value ) { /*check value first, then set _age*/ } public int getAge () { return this . _age ; } } and then consistently say: if ( person . getAge () > blah || person . getAge () < 10 ) { person . setAge ( 5 ); } After a while, the  get  and  set  become rather annoying. Providing dire...

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 So...

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 ');        ...

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)