November, 2014

...now browsing by month

 

Observations: @Html.EditorFor and @Html.TextBoxFor in MVC4

Monday, November 24th, 2014

A few tricks learned today when I was working on a email template manager project:

1) If an Action method was marked as [HttpPost] to handle the post event from a form, then there must be a same name Action without [HttpPost] attribute existing in the same controller or you will get a “Page cannot be displayed” error and there was very little debug info to go about.

For example, I have

[ValidateInput(false)]
[HttpPost]
public ActionResult FileUpload(EmailTemplateModel model)
{ //doing files upload }
then I must have a plain action with same name but different signature:

public ActionResult FileUpload()
{
EmailTemplateModel model = new EmailTemplateModel();

model.Attachments= PrepareAttachmentNewModel();

return View(model);

}

or I will get “Page cannot be displayed” error when I try to submit the form with one or multiple “file” html element.

2) Interestingly, when I return the model to view, only when I used @Html.EditorFor, I will be able to render the properties related to the file upload into each textbox; but then the other textboxes will become empty for those fields that were are already there on the form prior to posting the form. Instead, using @Html.TextBoxFor() will retain those values.

Have yet to understand the mechanism underneath, but for now these are my observations and just a quick note first.

Javascript method chaining example

Monday, November 10th, 2014

Javascript method chaining is basically a chain of method calls that instead of call multiple times, just get called once and “chained” to one single object instance – the singleton pattern here. Below are some working samples I created after reading a good reference at http://coursesweb.net/javascript/chain-methods-javascript-object; to try it out, just copy the codes below and paste it to a notepad and then render in any browser.

<html>
<body>
<div id="d1">
<h3>Method chaining example</h3>

<a href="javascript:getArea();">Get Area</a>
<br />
<a href="javascript:getPerimeter();">Get Perimeter</a>
</div>

</body>
</html>

<script type="text/javascript">
var rec=new Rectangule();

function getArea()
{
//alert(rec.Area(3,4)); //this is without chaining
alert(rec.SetParam(3,4).Area()); //chaining

}

function getPerimeter()
{

//alert(rec.Perimeter(3,4));
//method chaining
alert(rec.SetParam(3,4).Perimeter());

}
function Rectangule()
{
var a=0,b=0;

this.SetParam=function(a1,b1){
a=a1;b=b1;
return this; //this is what makes chaining possible.
}

this.Area=function(){
return a*b;

}

this.Perimeter=function(){
return 2*(a+b);

}

}

</script>