action方法中复杂类型的默认值

时间:2011-12-15 11:56:51

标签: asp.net-mvc

我在Controller中有一个动作方法,有一些类作为参数。如何为特定操作方法的类中的属性设置默认值?

2 个答案:

答案 0 :(得分:2)

我认为你可以使用自定义模型绑定器?所以你的行动方法如下:

public ActionResult Test([ModelBinder(typeof(ACustomModelBinder))] Models.TestC id)

模型绑定器看起来像:

public class ACustomModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // Bind anything that can be bound by default
        Models.TestC model = (Models.TestC)base.BindModel(controllerContext, bindingContext);

        // Set any other properties from the request (in your case, none)
        // model.SomeProeprty = bindingContext.ValueProvider.GetValue("AProperty").AttemptedValue;

        // Set the defaults that you want
        model.Name = "default name";
        model.Age = "27";

        return viewModel;
    }
}

答案 1 :(得分:0)

路线应该是这样的。  routes.MapRoute(                   “Default1”,//路由名称                     “{controller} / Test / {id}”,//带参数的URL                     new {controller =“Home”,action =“Test”,id = new MvcApplication19.Models.TestC(){Name =“Test11111”}}                     );

   // Model
   public class TestC
   {
    public string Name { get; set; }
   }
   // Action method in controller
   public ActionResult Test(Models.TestC id)
    {
        return Content(id.Name);
    }

这可以帮到你。如果没有提供更多信息。