基于ViewModel重用Controller Action

时间:2013-10-29 17:58:15

标签: asp.net-mvc asp.net-mvc-4

我将在我的网站上有一个注册表格,首先显示的是法定单位/合法。一旦被接受,它将显示主要注册表格。使用如下的ViewModel:

public class MyViewModel
{
    public int Readrules { get; set; }
    public int Coppa { get; set; }
}

public ActionResult Register(MyViewModel model)
{
    ... at this stage model.Readrules and model.Coppa will contain the values passed
        as query string parameters tat you could use here
}

我的想法是,如果我转到/register它会显示规则,然后/register?readrules=1它会显示注册表单。这是在PHP中完成的,但现在我正在迁移到ASP.NET ..

这样做的最佳方式是什么?我可以重定向到相同的操作,只是解析model.ReadRules的值,还是我必须使用多个操作?我希望将此保留在一个操作中,只需检查是否model.ReadRules == 1并显示董事会规则或注册表。

由于

2 个答案:

答案 0 :(得分:1)

您可以使用不同的控制器操作来显示规则,注册和处理注册,而不是重新使用注册操作,如下所示:

控制器操作:

public ActionResult BoardRules() 
{
    return View();
}

public ActionResult Register(MyViewModel model)
{
    if (model.ReadRules != 1)
        return RedirectToAction("BoardRules");

    return View();
}

public ActionResult Registration(MyViewModel model)
{
    if (model.ReadRules != 1)
        return RedirectToAction("BoardRules");

    //Process the registration

    return View();
} 

<强>查看:

BoardRules.cshtml:

@* HTML Displaying Rules *@
<a href="@Url.Action("Register", new { ReadRules = 1 })">Accept Rules</a>

Register.cshtml:

@using (Html.BeginForm("Registration", "[Controller Name]", new { ReadRules = 1 }))
{
    @* Form Fields *@
    <input type="submit" value="Process Registration" />
} 

Registration.cshtml

<h2>Congratz on Registering!</h2>

答案 1 :(得分:1)

public ActionResult Register()
{
    return View("boardrules");       //Default
}

public ActionResult Register(MyViewModel model)
{
    if (model.ReadRules == 1)
    {
        model.ReadRules++;            //Next time it won't be 1 but step 2
        return View("registration",model);
    }
    else
    {
      //Do IF or Case for other step
    }
    return View("boardrules");       //Default
}