模型绑定不适用于mvc1

时间:2011-08-19 18:42:57

标签: asp.net-mvc

我有课

public class Class2
{
    public string myName { get; set; }
    public string phone { get; set; }
    public jInformation jf { get; set; }
    public Class2()
    {

    }
}

public class jInformation
{
    public string name { get; set; }
    public string display { get; set; }
    public jInformation()
    {

    }
}

现在我的行​​动方法是

public ActionResult Test()
    {
        Class2 oClass = new Class2();
        return View("ViewPage1",oClass);
    }

帖子是

[AcceptVerbs(HttpVerbs.Post)]
    [ValidateInput(false)]
    public void Test(Class2 oClass)
    {
        String sTemp = oClass.myName;
        String sp = oClass.phone;
    }

我想用ViewContent创建一个stongley类型的视图作为“编辑”。因此,当我创建强类型视图时,它只是为myName和phone属性创建文本框。如何为jINformation类创建文本框?我正在使用MVC1和新手到MVC世界.......

我的CustomModel Binder看起来像

  public class Class2ModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;

        return new Class2()
                   {
                       myName = request.Form.Get("myName"),
                       phone = request.Form.Get("phone"),
                       jf = new jInformation { name = request.Form.Get("name"), display = request.Form.Get("display") }
                   };
    }
}

我用application_start注册了它。现在的问题是,我应该传递什么样的get和post方法?

3 个答案:

答案 0 :(得分:1)

您可以使用下面的文本框访问jInformation类的name属性:

<%= Html.TextBox("jf.name")%>

这假设您的视图的模型类是Class2。使用点表示法(jf.name),您可以访问子对象。这将是模型绑定,只是测试它。

控制器:

        [HttpGet]
        public ActionResult Index()
        {
            return View(new Class2());
        }

        [HttpPost]
        public ActionResult Index(Class2 class2)
        {
            return View(class2);
        }

查看:

答案 1 :(得分:1)

我之前的评论有点不对劲。默认的Model Binder适用于'Class2'。

我在这里测试过它。

控制器代码

public class TestController : Controller
{       
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult IndexPost()
    {
        Class2 cls = new Class2();
        UpdateModel(cls);
        return View(cls);
    }
}

视图代码(仅针对您的模型的表单)

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<Class2>" %>
<h2>Index</h2>
<% using (Html.BeginForm("indexpost","test")) {%>
<%: Html.TextBox("myName") %>
<%: Html.TextBox("phone")%>
<%: Html.TextBox("jf.name")%>
<%: Html.TextBox("jf.display")%>


<input type="Submit" value="submit" />
<%} %>

答案 2 :(得分:-1)

您的Model类'class2'中有自己的类'jInformation'。 MVC默认绑定器仅适用于标准数据类型(即int,string等)。它不会绑定您的类型。

如果您想绑定自己的类型,则必须编写自己的活页夹。

相关问题