Why the view doesn’t display the new values set in the post back method

April 26, 2013

In MVC, when you post back any changes, it’s recommended that you follow the PRG (Post-Redirect-Get) pattern to the View page. However, if you want to display the same model data back in the same request, there might be something you have to do.

Say if you have Edit method handles both Create and Update request, and you have a @Html.HiddenFor(m=>m.Id) in your view so that the update method knows which record to update:

 if( model.Id == 0 )
{
    int newId = InsertNewToDataBase( model );
   model.Id = newId; // <= this will not work
}
else
   UpdateDataBase(model);

return View(model);

After a new record is created, you want to set the new Id to the model so that the view will pick it up for the following edit request to work. No, this doesn’t work, @Html.HiddenFor(m=>m.Id) will still give you a zero.

Why is that?

MVC maintains a ModelState collection which holds the posted back data along with validation result. When you display the same view back with the posted back model, MVC will display the original value user enters on the browser with possible validation errors. For data integrity reasons, MVC ignores your direct change on the view model data when it binds the data using the Html helper method. So your model.Id = newId will NOT work.

The workaround is either use pure HTML control

<input type=’hidden’ value=’@Model.Id’ />

or remove the individual entry in the ModelState collection

ModelState.Remove(“Id”)

ModelState.Clear() works too. It will remove everything including the validation messages.


TFS – “The path … is already mapped in workspace …”

February 24, 2012

After installing some power too, my VS 2010 now always run under another admin account of me. So my previous mapping of the projects are lost and I can’t check out files to the original local path. The above error occurs if I try to remap the project to the same location. After some googling these tips helps:

In VS command line, use

  • c:\>tf workspaces /owner:*  (to show all workspace)
  • c:\>tf workspace /delete COMPUTER_NAME;USER_NAME (to remove the workspace)
  • c:\>tf workspace COMPUTER;USERNAME (this will open a GUI dialog to edit the workspace. The BEST option!)

I change my workspace to public so that any user can work on it (in case my VS switches back to my own account).


SQL command always times out after 30 seconds

February 22, 2012

One of my query takes more than 30 seconds to run. Even I set the “Connection Timeout=120″ in my connection string, it still throwing timed out exception. It turned out that the time out setting in the connection string is only for setting up the connection (as the name implies). To change the default 30 seconds time out for each individual database call, I need to set it on the SqlCommand object:

sqlCmd.CommandTimeout = 120; // 2 minutes


Src=” causes double page requests

October 12, 2011

A html tag with src=” (ie img) will cause the browser to try to request that resource at the same URL as the current page, hence causes double requests.


Formatting Dates, Times and Numbers in C#

November 12, 2010

Good reference (with examples)  http://www.4guysfromrolla.com/articles/111010-1.aspx


Crosstab query (2)

October 21, 2010

Part one here.

Another way to do vertical to horizontal query. Let’s have a table with sales_id, prod_id, sales_date, and sales_amount fields. This query will return 4 latest sales_id in 3 columns:

SELECT prod_id, (SELECT TOP 1 sales_id FROM table WHERE prod_id=s.prod_id ORDER BY sales_date) as sales_id1,

(SELECT TOP 1 sales_id FROM table WHERE prod_id=s.prod_id AND sales_id NOT IN (SELECT TOP 1 sales_id FROM table WHERE prod_id=s.prod_id ORDER BY sales_date) ORDER BY sales_date) as sales_id2,

(SELECT TOP 1 sales_id FROM table WHERE prod_id=s.prod_id AND sales_id NOT IN (SELECT TOP 2 sales_id FROM table WHERE prod_id=s.prod_id ORDER BY sales_date) ORDER BY sales_date) as sales_id3,

(SELECT TOP 1 sales_id FROM table WHERE prod_id=s.prod_id AND sales_id NOT IN (SELECT TOP 3 sales_id FROM table WHERE prod_id=s.prod_id ORDER BY sales_date) ORDER BY sales_date) as sales_id3

FROM table as s GROUP BY prod_id

Then you can join this view/sub-query to get detailed data for each row.

 


C# String Format examples for Double

September 24, 2010

From http://www.csharp-examples.net/string-format-double/

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.

[C#]

// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.

[C#]

// max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

Digits before decimal point

If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.

[C#]

// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567);      // "123.5"
String.Format("{0:00.0}", 23.4567);       // "23.5"
String.Format("{0:00.0}", 3.4567);        // "03.5"
String.Format("{0:00.0}", -3.4567);       // "-03.5"

Thousands separator

To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.

[C#]

String.Format("{0:0,0.0}", 12345.67);     // "12,345.7"
String.Format("{0:0,0}", 12345.67);       // "12,346"

Zero

Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).

Following code shows how can be formatted a zero (of double type).

[C#]

String.Format("{0:0.0}", 0.0);            // "0.0"
String.Format("{0:0.#}", 0.0);            // "0"
String.Format("{0:#.0}", 0.0);            // ".0"
String.Format("{0:#.#}", 0.0);            // ""

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.

[C#]

String.Format("{0,10:0.0}", 123.4567);    // "     123.5"
String.Format("{0,-10:0.0}", 123.4567);   // "123.5     "
String.Format("{0,10:0.0}", -123.4567);   // "    -123.5"
String.Format("{0,-10:0.0}", -123.4567);  // "-123.5    "

Custom formatting for negative numbers and zero

If you need to use custom format for negative float numbers or zero, use semicolon separator;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.

[C#]

String.Format("{0:0.00;minus 0.00;zero}", 123.4567);   // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567);  // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0);        // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.

[C#]

String.Format("{0:my number is 0.0}", 12.3);   // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3);          // "12aaa.bbb3"

Follow

Get every new post delivered to your Inbox.