http://reactjs.net/
http://facebook.github.io/react/

http://react-bootstrap.github.io/components.html

http://tutorialzine.com/2014/07/5-practical-examples-for-learning-facebooks-react-framework/

http://www.iteye.com/news/29544
http://www.syncano.com/reactjs-reasons-why-part-1/
http://www.williambrownstreet.net/blog/2014/04/faster-angularjs-rendering-angularjs-and-reactjs/


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 {this.state.name} . Click to change.
      </p>;
    }
});
 
React.renderComponent(<Hello name="World" />, document.body);




 
Categories: JavaSript | MVC

http://referencesource.microsoft.com/netframework.aspx

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.5.13.5.1View EULADownload
ASP.NET_MVC2.0View EULADownload
.Net4View EULADownload
.NET_3.5_sp1_redist50727.3053View EULADownload
ASP.NET_MVC3View EULADownload
Netfx_3.5.1_Win7SP13.5.1View EULADownload
NET4.5View EULADownload
Net4.5Update1View EULADownload


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

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

solustion:

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: Asp.net | 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. asp.net site said you can enable cors for webapi: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api . unfortunately, it require preview version of visual studio 2013.
  b. http://enable-cors.org/ 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";
        $.ajax({
            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);
                    //todo
                }               
            }
        });

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


 
Categories: Asp.net | 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});",
          callback,
          new JavaScriptSerializer().Serialize(model)),          
          "application/javascript");

        }
Client side you can open any page and try below:
$.get("http://localhost:45897/home/taskJsonP/1",
                  
                   function(value)
                   {
                       alert (value)              },
                   "jsonp"
             );


 
Categories: Asp.net | C# | Html5 | JQuery | MVC

 Web Api:  vs2013 only
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors
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
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
3. enable on apiController
namespace WebService.Controllers
{
    [EnableCors(origins: "http://myclient.azurewebsites.net", 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:

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

If you use SignalR.
http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-javascript-client#crossdomain
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableCrossDomain = true;
RouteTable.Routes.MapHubs(hubConfiguration);

Client code that specifies a cross-domain connection (with the generated proxy)
$.connection.hub.url = 'http://fabrikam.com/'
$.connection.hub.start().done(init);

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

var connection = $.hubConnection('http://fabrikam.com/');



 
Categories: JQuery | MVC | WCF

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

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

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

        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            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) {
                alert('ok!');
            })
            .fail(function (jqXHR, textStatus, err) {
                alert(err);
            });
    }


 
Categories: JQuery | MVC

1. add data-bind attribution to your dropdown

     @Html.DropDownListFor(m => m.SelectCafeBuildVersion, Model.AutoDaploymentData.CafeBuildVersions, "", 
new
 { @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:

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

That's it..

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


 
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.(http://msdn.microsoft.com/en-us/library/4xssyw96%28v=vs.71%29.aspx)
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 js...you can do other as Knockout give to you.

reference url


 
Categories: JQuery | MVC

A simple test,
$.ajax({
     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#

http://www.codeproject.com/Articles/305308/MVC-Techniques-with-JQuery-JSON-Knockout-and-Cshar

also need check this:

http://knockoutjs.com/documentation/introduction.html

http://blog.stevensanderson.com/2010/07/05/introducing-knockout-a-ui-library-for-javascript/


 
Categories: JQuery | MVC

October 2, 2012
@ 11:27 PM

Base on MVC definition from msdn http://msdn.microsoft.com/en-us/gg592073:

  • 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: Asp.net | 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()
        {
            Initialise();
        }

        //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:http://msdn.microsoft.com/en-us/library/ff660935%28v=pandp.20%29.aspx
             Container.LoadConfiguration();

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


the Config in Web.Config
<configuration>
  
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity>">
    <containers>
      <!-- <alias alias="ILoggingService" type="Widgets.WsunTest.Common.ILoggingService" />
     <namespace name="Widgets.WsunTest.Common" />
      <assembly name="Widgets.WsunTest" /> -->
      <container>        
          <register  type="Widgets.WsunTest.Common.ILoggingService,Widgets.WsunTest"
                mapTo="Widgets.WsunTest.Common.WsunLoggingService, Widgets.WsunTest" />   
       
      </container>
    </containers>
  </unity>
Reference:
http://msdn.microsoft.com/en-us/library/ff660935%28v=pandp.20%29.aspx


 
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>();
          
           logService.Logging(filterContext.Exception.Message,1);

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

        }
    }

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

            return View();
          
       }   
      

        public ActionResult Error(string message="unknow")
        {
            ViewBag.message=message;
            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)
                return;
            //do something to handele the exception
            filterContext.ExceptionHandled = true;
}
Easy to understand..buy I think Filter or actionFilter is more flexible easy to use.


 
Categories: C# | MVC

September 16, 2011
@ 12:44 AM
check the JQuery Ajax:
$.ajax({
type: "POST",
url: this.url,
data: form_data,
beforeSend: function() {
$('#ajaxDetails').addClass('progress');
},
error: function() {
$('#status').text('Update failed—try again.').slideDown('slow');
},
success: function() {
$('#status').text('Update successful!');
},
complete: function() {
$('#ajaxDetails').removeClass('progress');
setTimeout(function() {
$('#status').slideUp('slow');
}, 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;
$.ajax({
type:"GET",
url:"welcome.php",
data: data,
success: function (html) {
$('#message').html(html);
}
});
return false;
});
});


and MVC3 Ajax
@using (Ajax.BeginForm(       
"ActionName",
"ControllerName",
new AjaxOptions {
 UpdateTargetId = "modal-dialog",
OnFailure="searchFailed",
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"),
                        JsonRequestBehavior.AllowGet);
        }
2)Model:
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

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

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

    
    
In About.cshtml

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

About

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 : http://bassistance.de/jquery-plugins/jquery-plugin-validation/)


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

http://www.cnblogs.com/lori/archive/2011/07/18/2109817.html

前提:数据底层,使用的是MVC架构,对于数据表中的状态及相关字段,采用了枚举型进行对应

 

1 序列中不包含任何元素
  解决:将Single()改为DefaultOrSingle()

2 序列包含一个以上的元素
  解决:很多情况都是原始数据的问题

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

不要用LINQ自带的insert,就不会出现错误了

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的转化
   解决1,看看是否用了枚举类型,如果用了,应该先把IQueryable进行ToList,得到真正的数据后才能进行判断
   解决2,请看你的原始数据,很有可以是数据问题
   解决3,请看程序代码的关联表查询,很可能是它没有找出数据的问题

9  未将对象引用设置到对象的实例。
解决:查看数据库向数据实体赋值时,枚举类型的字段是否为null了,如果为null,就会出错

10    查询包含对不同数据上下文上所定义项的引用。
解决:查看底层工厂建立是否返回datacontext有问题,是否为空了。

11    枚举在LINQ中引发的异常:不支持SQL转换
    当枚举使用字符名称,没有数据,然它的数值存储在数据表中时,我们在返回数据时,必须在ToList()才行,否则就会出现这种问题
    例如:
     /// <summary>
     /// 以下是一个积分类型的枚举,一种类型对应数据表中同样类型的一个数值
     /// </summary>
   public enum PrestigeTypeCode
    {
           IAsk_Question,
            IAsk_Answer,
  }

  //表据表如下:
ID    描述        数值    枚举名称
1   提问           1    IAsk_Question
2   回答           1    IAsk_Answer

结论:当我们通过枚举去从数据库(SQLSERVer里)取数值时,必须要把结果集ToList()才行,如代码:
int value = new PrestigeTypesRepository().GetPrestigeTypes().ToList().Where(item => item.PrestigeTypeCode == prestigeTypeCode).Single().Amount;
如果,枚举的值,在枚举元素里读上,就不用去tolist()了

12 不能将 Null 值赋给类型为 System.Int32 (不可为 null 的值类型)的成员
解决:应该是数据的问题,Int类型的SQL表中出来了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 ASP.net 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);
            }
            else
                return View("Index");
        }
   protected RedirectResult CheckIfClassicPage(BillingProcess process)
        {
            string url = ViewMapUti.GetClassicUrl(process.CurrentStep, process.UidCustomerId);
            if (url != null)
                return Redirect(url);
            else
                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))
{
key="StartProcess";
}
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: Asp.net | MVC

Just deployed my MVC project to another server. that server has asp.net 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

 routes.MapRoute(
           "Default",                                              // Route name
           "{controller}/{action}.aspx/{id}",                           // URL with parameters
           new { controller = "Home", action = "Index", id = ""// Parameter defaults
       );
routes.MapRoute(
           "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..

Bingo!

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()) {%>       
UserName:
   <%=Html.EditorFor( model => model.UserName) %> 
<%=Html.ValidationMessage("UserName")%>
   Email:
   <%=Html.EditorFor( model => model.Email) %>   <%=Html.EditorFor( model => model.UserName) %>            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>
Just get this from Hariri's blog.
http://hadihariri.com/blogengine/post/2009/10/08/The-Principle-of-Least-Surprise.aspx

 
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
    {
        [Required()]
        [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">
//<![CDATA[
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

http://blogs.msdn.com/shaan/archive/2009/10/01/new-features-in-asp-net-mvc-2-preview.aspx

and I need the Client side validation feature.

here is some more blog

https://blogs.msdn.com/pietrobr/archive/2009/10/03/asp-net-mvc-2-preview-2-client-validation.aspx

http://blogs.msdn.com/rickandy/archive/2009/10/03/client-side-validation-for-mvc-2-p2.aspx

http://blogs.imeta.co.uk/HHariri/archive/2009/10/07/client-side-validation-in-mvc-2.0.aspx

http://hadihariri.com/blogengine/post/2009/10/06/Client-Side-Validation-in-MVC-20.aspx

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()) {%>
    
            <%=Html.EditorForModel()%>   
                <p>
                    <input type="submit" value="Save" />
                </p>
        <% } %>
    
    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 {
           [Required()]
           [Range(33,99)]
           public float Height { get; set; }
           [Required()]
           [StringLength(7)]
           public string Name { get; set; }
           [ScaffoldColumn(false)]
           public int ID { get; set; }
           public bool cool { get; set; }
           [DataType(DataType.EmailAddress)]
           [RegularExpression(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$")]
           public string email { get; set; }
           [DataType(DataType.MultilineText)]
           public string Bio { get; set; }
       }
    And here is Controller:
            [AcceptVerbs(HttpVerbs.Post)]
            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

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
    "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: Asp.net | 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 ASP.net programmer.
    I just think I may wait the next release of MVC and decide if to use it in my real projects.


     
    Categories: Asp.net | MVC