使用剃刀的单选按钮

时间:2015-06-08 21:51:58

标签: c# asp.net-mvc asp.net-mvc-4 razor

我有一个视图,上面有一个单选按钮组。单选按钮实际上与我的模型无关。它只是决定代码将采用什么路径(根据他们做出的选择来调用哪个存储过程)。如何获取控制器的选择值?

这样的事情:

<p>
    Select the option describing what you want to do:
    <br/>
    <br/>
    <label>@Html.RadioButton("selectProcess", "NewLetter", new { @id = "NewLetter" })Create a New Letter</label>
    <br />
    <label>@Html.RadioButton("selectProcess", "LetterInProgress", new { @id = "LetterInProgress" })Edit a Letter in Progress</label>
    <br/>
    <label>@Html.RadioButton("selectProcess", "GeneratedLetter", new { @id = "GeneratedLetter" })Edit a Letter that has been Generated</label>
    <br/>
    <label>@Html.RadioButton("selectProcess", "AppendGeneratedLetter", new { @id = "AppenGeneratedLetter" })Append a Generated Letter</label>

    <input type="submit" value="Go" />

</p>

我不确定这里是否需要这些ID,但我只想在我的控制器中有一个接收所选值的方法并调用一个存储过程或另一个(作为我的模型的一部分)...所选选项不代表模型中的字段。

我不是一个优秀的前端人员,所以我知道我可能会落后于此。

1 个答案:

答案 0 :(得分:0)

只需将HTML放在表单中,然后将其发布到控制器,就像您希望传回服务器的任何其他数据一样。

<form action="/Controller/HandlePost" method="post">
    <p>                                                         <!-- trimmed for clarity -->
        Select the option describing what you want to do:
        <br/>
        <label>@Html.RadioButton("selectProcess", "NewLetter", new { @id = "NewLetter" })Create a New Letter</label>
        <input type="submit" value="Go" />
    </p>
</form>

在服务器端,使用操作周围的[AcceptVerbs(HttpVerbs.Post)]仅接受帖子,然后重定向回带有视图的操作以清除帖子数据。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult HandlePost
{
    string selectProcess = Request.Form("selectProcess");

    // process selectProcess data however you need

    return RedirectToAction("Index", "Home");
}

如果由于某种原因你有一个控制器来处理发布数据并且如果通过get访问则返回视图,你可以这样做:

public ActionResult Index
{
    if (Request.HttpMethod.ToString() == "POST")
    {
        // handle POST data
        string selectProcess = Request.Form("selectProcess");
        // process selectProcess data however you need
        return RedirectToAction("Index", "Home");
    }

    // handle GET view
    return View();
}

仍需要POST部分内的重定向,以允许刷新浏览器并使后退历史记录无需重新发送帖子数据。

显然,Controller,HandlePost,Home,Index等将被您的控制器和动作名称替换。

正如@Stephen Muecke在评论中提到的那样,在使用RadioButton()方法避免无效HTML时,给出单选按钮ID是一种很好的做法。

相关问题