my test code:
var Hello = React.createClass({
  getInitialState: function() {
    return {name: 'test'};
  handleClick: function(event) {
    this.setState({name: 'abc'});
    render: function() {
        return <p onClick={this.handleClick}>
        Your name {} . Click to change.
React.renderComponent(<Hello name="World" />, document.body);

Categories: JavaSript | MVC

the download page only work under IE ;)

Available Source Code Components


Product NameVersionViewDownload
.NET8.0View EULADownload
dotnetfx1434_VistaWin2k8sp150727.1434View EULADownload
FXUpdate307450727.3074View EULADownload
ASP.NET_MVC1.0View EULADownload
WCF3.5SP1View EULADownload
WF3.5SP1View EULADownload
Dotnetfx_Vista_SP250727.4016View EULADownload
Dotnetfx_Win7_3. EULADownload
ASP.NET_MVC2.0View EULADownload
.Net4View EULADownload
.NET_3.5_sp1_redist50727.3053View EULADownload
Netfx_3.5.1_Win7SP13.5.1View EULADownload
NET4.5View EULADownload
Net4.5Update1View EULADownload

Categories: | C# | MVC | Visual studio 10/up | WCF

when use JqueryMobie in form, after submit, if redirect, it will have 302 find error.
jquery ajax submit was fired.


1. regular form, add data-ajax="false" in the from
2. MVC from,
 @using (Html.BeginForm(null,null,FormMethod.Post, new { data_ajax="false" }))

notice "data_ajax" in code bind, but it display data-ajax in the view.

Categories: JQuery | Mobile | MVC

Yesterday I test cross domain post against MVC successfully. So how about post to WebAPI?

But first try I failed and got error message like "Optional parameter 'user' is not supported by 'FormatterParameterBinding'.

after some research and test, I notice webapi [fromBody] parameters binding only take Model class as parameter.
//var data = "user=a" not owrk...string didn't have properties of user;
public string Test([FromBody] string user)
            return "user:" + user;

I have to change code like below:
public string Test([FromBody] User user)
            return "user:" + user;

  public class User
        public string Name { get; set; }

        public string Pwd { get; set; }
And test to post by jQuery
$.post('http://localhost:6660/api/task/test/0/t', { Name: 'a' ,Pwd:'b'});

and everything works

Categories: | JQuery | MVC

I don't want to use jsonP because it only can use "GET" method and all the data can be viewed on url.
After many search and failed test code. Finally I got below solution:

1. Enable CORS on server,
  a. site said you can enable cors for webapi: . unfortunately, it require preview version of visual studio 2013.
  b. site offer the methods to enable cors on IIS7, But it not works in my test.
  c. so I have to add the Access-Control-Allow-Origin=* to the response header by code myself.
    Simplest way is  adding this function in global.asax.cs
   protected void Application_BeginRequest(object sender, EventArgs e)
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

my test Action:
 public ContentResult Test(FormCollection formValues,string user="", string pwd="" )
            dynamic flexible = new ExpandoObject();
            flexible.UserName = user;

            var dictionary = (IDictionary<string, object>)flexible;
            dictionary.Add("IsSuccess", true);

            var re= JsonConvert.SerializeObject(dictionary); 
            return  Content(re);

2. It's not finish yet. you can see the correct response was return to the client in Fiddle or firebug, but the JQuery ajax call success not be fired. we have to do some more code on client side:
var loginUrl = 'http://localhost:6660/home/test';
        var data = "user=a&pwd=b";
            type: 'POST',
            url: loginUrl,         
            data: data,
            sucess:function(re) {
                //never reached here
            error: function (jqXHR, error, errorThrown) {
                //handle err
            complete: function (re, status) {
                if (status == 'success') {
                    var reObj = JSON.parse(re.responseText);

Yub!  date was get from cross domain server. this even working open html file directly.

Categories: | C# | JQuery | MVC

Server side code in controller:
     public ContentResult TaskJsonP(string callback,int id)
            var model = service.GetTaskDetails(new TaskDetailRequest() { Id = id });
            //return Json(model, JsonRequestBehavior.AllowGet);
            return Content(String.Format("{0}({1});",
          new JavaScriptSerializer().Serialize(model)),          

Client side you can open any page and try below:
                       alert (value)              },

Categories: | C# | Html5 | JQuery | MVC

 Web Api:  vs2013 only
1. install cors package through package manager console
Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebService

2. Add to api cofig
 public static class WebApiConfig
        public static void Register(HttpConfiguration config)
            // New code

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
3. enable on apiController
namespace WebService.Controllers
    [EnableCors(origins: "", headers: "*", methods: "*")]
    public class TestController : ApiController
        // Controller methods not shown...
4. some time you need $.support.cors = ture; before you make jsonp call

for WCF, congig it in webHttpbinding section of web.config:

        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />

If you use SignalR.
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableCrossDomain = true;

Client code that specifies a cross-domain connection (with the generated proxy)
$.connection.hub.url = ''

Client code that specifies a cross-domain connection (without the generated proxy)

var connection = $.hubConnection('');

Categories: JQuery | MVC | WCF

August 13, 2013
@ 10:12 AM
1. Config global to use WebApi in MVC4
 protected void Application_Start()



2. Add your mapping in App_Start folder WebApiConfig.cs
public static class WebApiConfig
        public static void Register(HttpConfiguration config)
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
             name: "GetTaskApi",
             routeTemplate: "api/{controller}/{action}/{id}/{token}",
             defaults: null
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }

            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }

            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
3 Add you WebApi Controller
public class TaskController : ApiController
        // http://localhost:45897/api/task/1
        public TaskDetailResponse Get(int id)
                    return  apiService.GetTaskDetails(new TaskDetailRequest(){Id=id});
        // http://localhost:45897/api/task/gettask/1/testtoken
        public TaskDetailResponse GetTask([FromUri]TaskDetailRequest request)
            var response = apiService.GetTaskDetails(request);
            return response;


4. in Firefox and Chrome, if you visit the link, it will return xml, but in IE, it will let you save a json file

5. User jQuery.getJSON to call the api
function getData() {
        var apiUrl = 'api/task';
        var id = 1;
        $.getJSON(apiUrl + '/' + id)
            .done(function (data) {
            .fail(function (jqXHR, textStatus, err) {

Categories: JQuery | MVC

1. add data-bind attribution to your dropdown

     @Html.DropDownListFor(m => m.SelectCafeBuildVersion, Model.AutoDaploymentData.CafeBuildVersions, "", 
 { @class = "", @data_bind = "options: cafeBuildVersions,optionsText: 'Text',optionsValue:'Value'" })       
Notce here is "@data_bind", it will change to "data-bind" in the HTML automatictly.

2. in the ajax Call get json object from backend, and add a a viewmode:

                type: "post",
                url: "MyController/RefreshModelData",
                success: function (model) {                   
                 var   viewModel = {
                        cafeBuildVersions: ko.observableArray(model.AutoDaploymentData.CafeBuildVersions)
                error: function (v) {
                    alert("data error!");

That's it..

if not in can get the modeldata from model do it in the View:
var modelData = @Html.Raw(Json.Encode(Model));
<script type="text/javascript">
    var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;

Categories: JQuery | MVC

If the symbol is defined, the call is included; otherwise, the call is omitted. Conditional methods provide a cleaner, more elegant alternative to enclosing the method call in #if conditionalSymbol...#endif preprocessor directives.(
Using the Conditional attribute, you can isolate functions that should be part of your classes only when a particular environment variable is defined or set to a certain value.
The Conditional attribute generates more efficient IL than #if /#endif  does. It also has the advantage of being applicable only at the function level, which forces you to better structure your conditional code. (Effective C#:50 Specific Ways to Improve Your C# by Bill Wagner (Mar 15, 2010))

Categories: C# | IoC | MVC | Visual studio 10/up

December 14, 2012
@ 02:16 PM
To transfer the model object from MVC c# object to Knockout  javascript data object:
var modelData = @Html.Raw(Json.Encode(Model));
With the ModelData in can do other as Knockout give to you.

reference url

Categories: JQuery | MVC

A simple test,
     url: "http://localhost:45166/userAdmin/UserAccountInfo/?child=true&json=true",
     dataType: 'jsonp',
     success: function(json) {

         //jsonp return a javascript
         // callback({json:value})
     error: function() {


in the Controller

return a javascript as ActionResult:
return JavaScript("alert({'TEST'})");
the javascript can be run in the client site.

Categories: JQuery | MVC

October 2, 2012
@ 11:46 PM
MVC Techniques with jQuery, JSON, Knockout, and C#

also need check this:

Categories: JQuery | MVC

October 2, 2012
@ 11:27 PM

Base on MVC definition from msdn

  • Models: Model objects are the parts of the application that implement the domain logic. Often, model objects also retrieve and store model state in a database.
  • Views: Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be the edit view of Albums that displays text boxes and a drop-down list based on the current state of an Album object.
  • Controllers: Controllers are the components that handle user interaction, manipulate the model, and ultimately select a view to render the UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction.

So Create a ViewModel for each Views, ViewModels should be a DTO or Plain Object.   and Models are Factories to Generate ViewModels.

The MVVMC should be like this:

for example UserContacts page:

UserContactsController ->UserContactsModel->UserContactsViewModel->UserContactsView

Controller ask UserContactModel for UserContactsViewModel and fill the UserContactsView and return it.

and there is another View Model or domain object UserContact.

UserContactsViewModel is Model of UserContactsView,

UserContactsViewModel has something like List<UserContact>

there should be couple of helpers can be called by UserContractsModel.

Categories: | MVC

September 26, 2012
@ 03:29 PM
I found this piece of code from stackflow, and I think it was very useful when you want to use a enum to a MVC dropdown.

    public static class EnumUtility
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                         select new { Id = e, Name = e.ToString() };

            return new SelectList(values, "Id", "Name", enumObj);

Categories: C# | MVC

  public static class UnityIOC
        public static IUnityContainer Container;
        private static bool _isInited ;
        //Make it not dependends the application_start, 
        //this make the Controller can be tested in UnitTest tools
        static UnityIOC()

        //call by global.asax application start for MVC
        public static void Initialise()
            if (!_isInited)
                _isInited = true;
                Container = BuildUnityContainer();
                DependencyResolver.SetResolver(new UnityDependencyResolver(Container));
                //to use this container in mvc
                // DependencyResolver.Current.GetService(Type)  just resolve in ioc containner

        private static IUnityContainer BuildUnityContainer()
            Container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers
            // e.g. container.RegisterType<ITestService, TestService>();            
          //  Container.RegisterType<Widgets.WsunTest.Common.ILoggingService, Widgets.WsunTest.Common.WsunLoggingService>();

            //load web.config ref:

                <WsunTest.ViewModel.IWidgetModelFactory<WsunTest.Models.IWsunRequest, WsunTest.Models.WsunResponse>,
                .RegisterType<WsunTest.Models.IWsunRequest, WsunTest.Models.WsunRequest>();
            return Container;

the Config in Web.Config
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  <unity xmlns=">">
      <!-- <alias alias="ILoggingService" type="Widgets.WsunTest.Common.ILoggingService" />
     <namespace name="Widgets.WsunTest.Common" />
      <assembly name="Widgets.WsunTest" /> -->
          <register  type="Widgets.WsunTest.Common.ILoggingService,Widgets.WsunTest"
                mapTo="Widgets.WsunTest.Common.WsunLoggingService, Widgets.WsunTest" />   

Categories: C# | IoC | MVC

September 18, 2012
@ 07:49 PM
Just Implement a Controller Error Handler call "LogError":
  public class LogError : FilterAttribute, IExceptionFilter
        public void OnException(ExceptionContext filterContext)
           ILoggingService logService = DependencyResolver.Current.GetService<ILoggingService>();

            //redirect to customer error page
            filterContext.Result =
               new RedirectToRouteResult(
                   new RouteValueDictionary{{ "controller", "WsunTest" },
                                                 { "action", "Error" },
                                                 { "returnUrl",    filterContext.HttpContext.Request.RawUrl }
            filterContext.ExceptionHandled = true;


And below is the controller, I put the filter on the top of Controller:
    public class WsunTestController : Controller
       public ActionResult Index()
                throw  new Exception("test exception message");

            return View();

        public ActionResult Error(string message="unknow")
            return View();


There is another way is override the parent controller:
 protected override void OnException(ExceptionContext filterContext)

            // Don't interfere if the exception is already handled
            if (filterContext.ExceptionHandled)
            //do something to handele the exception
            filterContext.ExceptionHandled = true;
Easy to I think Filter or actionFilter is more flexible easy to use.

Categories: C# | MVC

September 16, 2011
@ 12:44 AM
check the JQuery Ajax:
type: "POST",
url: this.url,
data: form_data,
beforeSend: function() {
error: function() {
$('#status').text('Update failed—try again.').slideDown('slow');
success: function() {
$('#status').text('Update successful!');
complete: function() {
setTimeout(function() {
}, 3000);

to get the from data:
var form_data = $("form").serialize();
var form_data_array = $("form").serializeArray();
a simple example:
$(document).ready(function() {
$('#submit').click(function () {
var name = $('.uname').val();
var data = 'uname=' + name;
data: data,
success: function (html) {
return false;

and MVC3 Ajax
@using (Ajax.BeginForm(       
new AjaxOptions {
 UpdateTargetId = "modal-dialog",
OnBegin = "Dialog.Updating()",
OnSuccess = "Dialog.Update({title:'Select Friends'})"
})) {
… <input type="submit" value="Next" />

Categories: JQuery | MVC

September 10, 2011
@ 01:05 AM
I created a new MVC project, and test the remote validation in the about page.

1)Controller Home:
               public ActionResult ValidateTestName(string testName)
            return Json(!testName.Equals("test"),
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MvcApplication1.Models
    public class AboutModel
        [Remote("ValidateTestName", "Home", ErrorMessage = "this Name already be used.")]
        public string TestName { get; set; }

        [Range(20, 44)]
        public int Age { get; set; }
In _Layout.cshtml:

In About.cshtml

@model MvcApplication1.Models.AboutModel
    ViewBag.Title = "About Us";


Put content here. @using (Html.BeginForm()) { @Html.EditorForModel(); "submit" value="Submit" /> }

It is working perfect under FireFox 6:

but not working in my IE9 :(...
I have downloaded Jquery.Validation 1.8.1 try to fix this issue, but looks still unlucky.
(Jquery.Validation site :

but this post in stack overflow said it tested in
Chrome 10.0, IE9 and FireFox 4.0
Categories: | MVC



1 序列中不包含任何元素

2 序列包含一个以上的元素

3 不能在已使用的实体上添加新实体
4 Duplicate key is already ,
  3,4的解决为:用  base._db.ExecuteCommand()进行SQL语句的重写,


5  未将对象引用设置到对象的实例。 值不能为空。参数名: source。
   解决:  this.iProduct_ProductFilesRepository.Insert(_entity.Product_ProductFile.Cast<Entity.IDataEntity> ().ToList());,当遇到将list实体类型换为接口list规范时,应该用.Cast<接口类型>().ToList()

6 查询参数不能为“System.Object”类型。
解决:这是因为在LINQ的ExecuteCommand不理解空值,当我们传递的参数为 null 时,就会出现这个问题,解决方法是,在为实体加string.empty这个空值属性

7  Incorrect syntax near '@p0'.
解决:查看我们的SQL代码,被编译成了什么,可能是多个括号之类的。如:delete from users where (userid={0},这很明显是不对的,哈哈

8 不支持SQL的转化

9  未将对象引用设置到对象的实例。

10    查询包含对不同数据上下文上所定义项的引用。

11    枚举在LINQ中引发的异常:不支持SQL转换
     /// <summary>
     /// 以下是一个积分类型的枚举,一种类型对应数据表中同样类型的一个数值
     /// </summary>
   public enum PrestigeTypeCode

ID    描述        数值    枚举名称
1   提问           1    IAsk_Question
2   回答           1    IAsk_Answer

int value = new PrestigeTypesRepository().GetPrestigeTypes().ToList().Where(item => item.PrestigeTypeCode == prestigeTypeCode).Single().Amount;

12 不能将 Null 值赋给类型为 System.Int32 (不可为 null 的值类型)的成员

Categories: MVC

I am working on a project that has page flow controlled by a Controller of the MVC framework. For some complcated pages I must use the Classic WebForm type, rather than a regular View page. 
When the page in Classic WebForm has finished its job, the page needs to redirect back to the MVC controller and go to next page decided by the Business logic in the Controller

Here, I listed some redirect code that may be useful.

In classic Web Form page
  protected void btnContinue_Click(object sender, EventArgs e)
            BillingProcess process = CurrentProcess;//BillingmanagementService.GetProcess(Uid);
            process.CurrentStep = BillingManagementStep.TempCreditStart;//this is required, to make sure the current step
            Response.Redirect(ViewMapUti.GetProcessUrl("continue", process.CurrentStep, Uid));
           // Response.Redirect(string.Format("/BillingManage/Process/continue/{0}/{1}",process.CurrentStep, Uid));

In Controller
    protected ActionResult GoToPage(BillingProcess process)
            if (process != null)
                RedirectResult rUrl = CheckIfClassicPage(process);
                if (rUrl != null)
                    return rUrl;
                return View(ViewMapUti.GetMapPage(process.CurrentPage), process);
                return View("Index");
   protected RedirectResult CheckIfClassicPage(BillingProcess process)
            string url = ViewMapUti.GetClassicUrl(process.CurrentStep, process.UidCustomerId);
            if (url != null)
                return Redirect(url);
                return null;


   In Help class ViewMapUti.cs
    public class ViewMapUti

// this need put in MapHelper.cs in the root public static String GetMapPage(string key)
///TODO:we should have a map in xml do defined which current viwe will be used. ///for example, we have made the change of Page1, rename to page2, but want keep the page2, ///just need add the page1 page2 in the mapfile if(key.Equals("initial",StringComparison.CurrentCultureIgnoreCase))
return key;
public static string GetProcessUrl(string actionButton, BillingManagementStep step, long uid)
return GetProcessUrl("Process", actionButton, step, uid);
public static string GetProcessUrl(string view, string actionButton, BillingManagementStep step, long uid)
if (view == null )
return GetHomeUrl();
/// 1.{controller}/{step}/{uid}/{action}.aspx/{actionButton} // return string.Format("/{0}/{1}/{2}/{3}.aspx/{4}", "BillingManage", step,uid, view, actionButton); ///2. /BillingManage/Process.aspx?uid=121&actionButton=process&step=ProcessingRequest /// return GetVirtualPath() + string.Format("/{0}/{1}.aspx?uid={2}&actionButton={3}&step={4}", "BillingManage", view, uid, actionButton, step);
public static string GetHomeUrl()
return HttpRuntime.AppDomainAppVirtualPath+"BillingManage/Index.aspx";
public static string GetClassicUrl(BillingManagementStep step, long uid)
if (step == BillingManagementStep.StartProcess ||step==BillingManagementStep.Initial)
//if need classic //Don't use transfer, it will cause javascript error in Ajax sometime(not every time). //Server.Transfer("/Classic/startProcess.aspx?uid=" + uid); return (GetVirtualPath() + "/Classic/startProcess.aspx?uid=" + uid);

else if (step == BillingManagementStep.EcouponCredit)
return (GetVirtualPath() + "/Classic/EcouponCredit.aspx?uid=" + uid);
else if (step == BillingManagementStep.TempCreditStart)
return (GetVirtualPath() + "/Classic/TempCredit.aspx?uid=" + uid);
return null;
public static string GetVirtualPath()
return HttpRuntime.AppDomainAppVirtualPath.Equals("/") ? "" : HttpRuntime.AppDomainAppVirtualPath + "/";


Categories: | MVC

Just deployed my MVC project to another server. that server has framework 3.5 sp1 installed, but no MVC.

1. At First I got Http 403 Error, that because the server didn't support url like "/Home/Index/", this error message said that you don't have permission to browser the direction.  If you have full control of the web server, you can configure the IIS to recongize your MVC url, but it not works in many situation,  that's because the change may affect other applications in that server.

One of the solution is: Let your url looks like regular aspx page. for example "Home/Index.aspx".

Here is my new route map definition in global.ascx

           "Default",                                              // Route name
           "{controller}/{action}.aspx/{id}",                           // URL with parameters
           new { controller = "Home", action = "Index", id = ""// Parameter defaults
           "Process",                                              // Route name
           "{controller}/{step}/{uid}/{action}.aspx/{actionButton}",                           // URL with parameters
            new {controller = "BillingManage", action = "Index",step=0, actionButton="", uid = "0"// Parameter defaults

2. Then it still not works in the site root. I need add a default.aspx file in the site root. In the default.aspx file, you can redirect the page to your real default "Home/Index.aspx".

3. But there are still another error happen, MVC.dll not found.  Ahha! that's easy, just need copy MVC.dll to the bin folder.

Find the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies

copy System.Web.Mvc.dll and Microsoft.Web.Mvc.Build.dll to your bin..


4. The last note of today: you can't put Telerik scriptmanager  with the MicrosoftMvcAjax.js in the same page , the ajax javascipt tell you "'sys.mvc.asynchyperlink' is null or not an object".

Categories: MVC

If you don't like the Layout create by template of MVC ValidationHelper, You can break it apart, and make your own.

    <% using (Html.BeginForm()) {%>       
   <%=Html.EditorFor( model => model.UserName) %> 
   <%=Html.EditorFor( model => model.Email) %>   <%=Html.EditorFor( model => model.UserName) %>            <p>
                <input type="submit" value="Save" />
    <% } %>
Just get this from Hariri's blog.

Categories: MVC

1. Create a Model for the View if you don't have one.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BillingManagementWebGUI.Models
    public class IndexPageModel
        [Range(1, 99)]
        public long CustomerId { get; set; }

2. Add Javascript to the SiteMast, becareful you must keep the Same Order like below.

 <script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>" type="text/javascript"></script> 
 <script src="<%= Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
 <script src="<%= Url.Content("~/Scripts/MicrosoftMvcJqueryValidation.js") %>" type="text/javascript"></script>
3. Update the View
 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<BillingManagementWebGUI.Models.IndexPageModel>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">      Start Page </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Billing Management Start Process</h2> <span id="msg" style=" color:Red;"><%=Html.Encode(TempData["MSG"]) %></span><br /> <% Html.ClientValidationEnabled = true; %> <% using (Html.BeginForm("StartProcess","BillingManage") ){ %> <fieldset> <%= Html.ValidationSummary("Broken stuff:") %> <%= Html.EditorForModel() %> <input id="btnStartProcess" value="Process" name="btnStartProcess" type="submit" /> </fieldset> <% } %> </asp:Content>

4. Run the code

here is the Magic piece:
<script type="text/javascript">
EnableClientValidation({"Fields":[{"FieldName":"CustomerId","ValidationRules":[{"ErrorMessage":"The field CustomerId must be between 1 and 99.","ValidationParameters":{"minimum":1,"maximum":99},"ValidationType":"range"},{"ErrorMessage":"The CustomerId field is required.","ValidationParameters":{},"ValidationType":"required"}],"ValidatorId":"form0_CustomerId_validator"}],"FormId":"form0"}, null);
//]]> </script>

Categories: MVC

here is some blog for MVC2 Preview 2

and I need the Client side validation feature.

here is some more blog

Pietro Brambati's blog: 

  • use Html.EnableClientValidation method on the View file
  • insert three javascript files : jquery-1.3.2.js, jquery.validate.js, MicrosoftMvcJQueryValidation.js. These files are included in the Scripts directory coming with ASP.NET MVC 2 Preview 2 project template

    Hariri find only with "using" the javascript code will be render

    <% Html.ClientValidationEnabled = true; %>
      <% using (Html.BeginForm()) {%>
                    <input type="submit" value="Save" />
        <% } %>
    here is the Model code:
      public class Customer
         [Required(ErrorMessage = "First name is required")]
         public string FirstName { get; set; }
         [Required(ErrorMessage = "Last name is required")]
         public string LastName { get; set; }
         public string Email { get; set; }
    public class Pals {
           public float Height { get; set; }
           public string Name { get; set; }
           public int ID { get; set; }
           public bool cool { get; set; }
           public string email { get; set; }
           public string Bio { get; set; }
    And here is Controller:
            public ActionResult Edit(int id, Customer customer)
                if (ModelState.IsValid)
                    // TODO: Do whatever...
                    return RedirectToAction("Index");
                return View(customer);

    I will do post some my code in later.

    Categories: MVC

    Currently I am working on a project are using ASP.NET MVC, and I need reuse some user controls with Telerik Controls,
    As you know, many of those user controls for WebForm need enable ViewSate.
    So I had combined both new MVC and old WebForm pages in this project.
    and I had encountered and solved many issues both for integration and MVC
    I write some key points here as my collections and want to share with my visitors.
    Here is an article about adding MVC to regular website :link

     1. setup Route in Global.asax

    public static void RegisterRoutes(RouteCollection routes)

    // routes.IgnoreRoute("Classic/{resource}.aspx?{*requestUrl}"); //the ? is not allow in the route config
    routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); //All .aspx regard as webform.
    routes.IgnoreRoute("{resource}.ash/{*pathInfo}"); //other type need escape
    routes.IgnoreRoute("Classic/{resource}.aspx/{*pathInfo}"); //I put my webform files in classic folder


    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = "" } // Parameter defaults

    2. Make your old UserControls work

    3. Fix those weird problems of Visual Studio 2008
    After copy the Classes such as "BaseUserControl.cs" to MVC project, whatever how many times I clean and rebuild the project, Those classes always can't be found by other classes.
    And another issue happen frequently is the Pages have using Telerik controls, always have error message 'Error Creating Control' at design time.
    After some research, I found  those step will solve these issues like a magic.

       step 1. Close your Visual studio 2008 .
       step 2. Go to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\ folder, delete all sub directories.
       step 3. Go to C:\Documents and Settings\yourname\Local Settings\Application Data\Microsoft\VisualStudio\9.0\ProjectAssemblies\
                  Delete all sub diretories.
       step 4. Restart.

    And some people said, if copy the Telerik dlls to Global assembly will fix Telerik issue.

    Categories: | MVC | Telerik Controls | VS 2008

    June 9, 2009
    @ 05:29 PM
    Just spend some time to try the ASP.NET MVC framework.
    MVC it self is not a new stuff,  there are many famous frameworks in JAVA like Struts.
    In the .Net, you also can find some open source MVC framework, like monoRail in castle project.
    I am just surprised why Microsoft release its MVC framework so late.

    Them ASP.NET MVC solve the  problem that you can't do Unit Testing in the ASP.Net websites. it make the responsibility of each parts more clear.
    And the Url rewrite can let you have User and SEO friendly url easily.
    It get rid of viewstates in "post back", which will make the page size smaller and improve the performance.
    And especially in AJAX post back, the response time will much faster, because it don't need load any other controls in that page and their viewstates.

    but I just feel hesitated to use MVC in my new project for those reasons:

    1. Not as easy and fast as the web form Page Control model. It may good for some complicate and big application. 
    2. Don't have good support by IDE, I may missing some plug-in or starter kit, but I think do MVCp rogramming  in VisueStudio 2100 may be easier than current VS2005/2008.
    3. Little bit complicate to build a simple page. write a View give me some trouble, and spend more time than I expect.
    4. There is not controls and components available for us to using in the project to save developing time. But I know some components vendors will support MVC soon, will find that out when got chance.
    5. It is not easy to find a good sample project and documents. Some books are in releasing or just published. I am still waiting it come out and want to check if them are worthy to buy.

    The MVC is the first release from Microsoft. As well know the first product from Microsoft always looks ugly and silly. but it always have good chance to bet it competitor.

    Though I said something bad to MVC, but I still think it is a good thing for programmer.
    I just think I may wait the next release of MVC and decide if to use it in my real projects.

    Categories: | MVC