I am working on an asp.net MVC 3 application.
I have a C# function that takes a string as an input, formats it and then returns the formatted string.
I have a .cshtml file where I fill data in a webgrid.
When filling the data in the webgrid, I want to format it first through a C# function and then fill the results.
In asp.net I can simply use the code behind to do it. but I am new to MVC 3 so any suggestions on how to do it is greatly appreciated.
I heard it should be done in the action. can you help me on how to do that?
the C# function look like this
public string FormatString (string input)
{
// I Format the string and return it
}
the webgrid look like this
<div id="GridDiv">
@grid.GetHtml(
htmlAttributes: new { id = "grid" },
tableStyle: "grid",
headerStyle: "header",
rowStyle: "row",
footerStyle: "footer",
alternatingRowStyle: "altRow",
columns: grid.Columns(
grid.Column("Name", "Name", style: "Centered", canSort: true),
grid.Column("Address", "Address", canSort: true),
grid.Column("City", "City", canSort: true),
grid.Column("PhoneNumber", "Phone Number", style: "Centered"),
))
I want to format the Name, Address, City, and PhoneNumber
Thanks a lot for any help
OK, personally I have never used the Grid helper, but I assume this would be the general direction.
Let’s say the Name/Phone/City/Address are properties of a Person class.
Build an appropriate view model
Use it in controller action
And then use this model on your page, so when you pass PhoneNumber, City and Address to the grid in the view, you’ll have them pre-formatted.
EDIT: Regarding ‘where to put the FormatString method’
As I see it, you can put it in the ‘Person’ model class if you’re going to use it in the Person-related business only:
(If the Person class is generated from e.g. EF, you can do it in a different file so it looks neat, like below)
or
or if you’re feeling fancy (or – more practically – you’re going to use it in any other situation for string formatting), you can define the method as a string extension for convenience:
And then:
PhoneNumber = PhoneNumber.FormatString();