【问题标题】:How to send data from view to controller in MVC3如何在 MVC3 中将数据从视图发送到控制器
【发布时间】:2012-11-27 18:36:50
【问题描述】:

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

这里是登录动作控制器

[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());
}

【问题讨论】:

  • 你的观点在哪里?你可以使用@using (Html.BeginForm("ActionName","ControlerName",FormMethod.Post,new{enctype = "multiparrt/form-data}){ "这里是你的 html"}
  • 您的意思是使用带有 hidden.For 的 html.begin 表单,但我想将此参数发送多个控制器方法
  • 如果你想发送这个参数不止一个控制器方法,那么你应该使用json post

标签: asp.net-mvc-3


【解决方案1】:

你必须在你的动作方法中添加一个参数:

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" />
}

【讨论】:

    【解决方案2】:

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

    <form action = "yourcontroller/youraction" method = "POST" enctype = "multiparrt/form-data">
    

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 2016-06-25
      • 1970-01-01
      • 2014-08-18
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      相关资源
      最近更新 更多