Asp.net mvc MVC:post,将表单值捕获到页面模型的属性中

Asp.net mvc MVC:post,将表单值捕获到页面模型的属性中,asp.net-mvc,model-view-controller,Asp.net Mvc,Model View Controller,好吧…这可能有点倒退,但我只需要在一个地方做 我有一个模型 public class LoginModel : xxx.Models.PageVars { public Item.LoginAttempt LoginAttempt { get; set; } public LoginModel() { // does a bunch of stuff here...mainly to set the layout properties from PageVar this.L

好吧…这可能有点倒退,但我只需要在一个地方做

我有一个模型

public class LoginModel : xxx.Models.PageVars
{

public Item.LoginAttempt LoginAttempt { get; set; }

public LoginModel()
{
    // does a bunch of stuff here...mainly to set the layout properties from PageVar

    this.LoginAttempt = new Item.LoginAttempt();
}
}
登录尝试目前是一个简单的obj

    //  login attempt
public class LoginAttempt
{
    public string Email { get; set; }
    public string Password { get; set; }
}
我的控制器

    public ActionResult Login()
    {

        return View("Login", new Models.LoginModel());
    }


    [HttpPost]
    public ActionResult LoginAttempt(LoginAttempt model)
    {
        return View("Login", model);
    }
在我看来 @型号xxx.Models.LoginModel

是否有一种方法可以将LoginModel中的obj/model属性用于@model

我可以从FormCollection或request中获取值,但…这不是最佳值

想法


tnx

为什么不让form post controller操作接受父模型LoginModel而不是LoginAttent?这样,默认的MVC模型绑定应该自动将提交的值解析到LoginModel中,您就可以访问LoginAttent

如果不是,则表单需要在表单上的属性名称中使用前缀值。当您使用TextboxFor、DropdownListFor等时,这将自动完成


在您的示例中,表单字段的名称应以loginattent.Email等开头,GET的模型应与您的帖子的模型匹配。否则,你就不能在同一个场地上比赛。为了允许将POST中的数据绑定到模型,HTML助手将生成与视图模型中属性的访问路径匹配的名称。换句话说,在表单中,基于LoginModel的模型,您的字段名将是LoginAttest.Email和LoginAttest.Password。但是,在POST操作中,您只接受LoginAttest,因此modelbinder希望看到电子邮件和密码的数据,而它找不到这些数据


实际上甚至不需要这个嵌套类。只需将电子邮件和密码字段直接放在LoginModel上,并将其用于视图和POST参数。这样,您就不会有任何问题,因为一切都会匹配。

我看到它有两种工作方式。第一种方法是将LoginAttest模型参数重命名为

[HttpPost]
public ActionResult LoginAttempt(LoginAttempt loginModel)
{
    return View("Login", model);
}
但我会使用BindPrefix选项

但是,您不能将LoginAttest类型的模型返回到视图中,因此,如果您打算这样做,则必须做更多的工作才能使其正常工作。如果成功,您可能应该重定向到其他页面,而不是返回登录视图。其他方式返回新的LoginModel{LoginAtTest=model}

[HttpPost]
public ActionResult LoginAttempt([Bind(Prefix="LoginModel")] LoginAttempt model)
{
    return View("Login", model);
}