1

大家好,我想问一下如何将数据从视图发送到控制器?我想用我的控制器和视图描述我的问题,如下所示

这是登录动作控制器

[HttpPost]
public ActionResult Login(Panel model, string Username, string Password, string CaptchaValue, string InvisibleCaptchaValue)
{
    bool cv = CaptchaController.IsValidCaptchaValue(CaptchaValue.ToUpper());
    bool icv = InvisibleCaptchaValue == "";

    if (!cv || !icv)
    {
        ModelState.AddModelError(string.Empty, "The Captcha Code you entered is invalid.");
    }

    if (ModelState.IsValid)
    {
        if (model.Username == Username && model.Password == Password)
        {
            FormsAuthentication.SetAuthCookie(model.Username, false);
            return RedirectToAction("index", "Home");
        }
        else
        {
            ModelState.AddModelError("", "Check your name or password");
        }
    }
    return View();
}

因此,当用户登录时,重定向到主页/索引视图。此时一切正常。

这是我的索引视图:

[Authorize]
public ActionResult index()
{
    return View();
}

我的问题是如何保存用户的密码参数并从索引视图发送到不同的控制器以在控制器方法中使用此参数但是如何?例如,我想在 where 子句中的 index_test 控制器方法中使用密码参数,但首先我需要从 index.html 发送这些数据。

public ActionResult index_test()
{
    return View(db.contents.Where(x => x.test_parameter== password).ToList());
}
4

2 回答 2

3

您必须向您的操作方法添加一个参数:

public ActionResult index_test(string password) { ...

在您的视图中,您可以通过标准链接将数据发送到操作:

@Html.ActionLink("Click me", "index_test", "Controller", 
                                  new { password = "StringOrVariable")

或者通过做一个表格帖子:

@using(Html.BeginForm("index_test")) { 
    <input type="hidden" name="password" value="mypassword" />
    add some fields
    <input type="submit" value="Send" />
}
于 2012-11-27T09:48:59.980 回答
0

例如,在您的视图中,将表单发送回控制器

<form action = "yourcontroller/youraction" method = "POST" enctype = "multiparrt/form-data">
于 2012-11-27T09:22:34.783 回答