如何在表单提交时将复选框值传递给控制器​​,然后返回数据以查看?

时间:2018-10-03 17:38:39

标签: asp.net-mvc post

在“我的视图”中,我在一些用户记录的前面放置了一个复选框。当我选中一个复选框并单击“提交”按钮时,所选的复选框值(用户ID )将发送到控制器。目前,我已成功在模型中收到电子邮件,但无法将数据库结果重新显示。

客户视图:

@using (Html.BeginForm())
{ 
 <table class="table table-responsive">
 @foreach (var s in Model)
 {
  <td id="list"><input type="checkbox" name="ids" id="ids" value="@s.Id" /></td>  
 }
  <tr>
    <td><button class="btn btn-primary" id="sendmail" type="submit">Send Email To Customers</button></td>
  </tr>
 </table>      
}
@if (TempData["Emails"] != null)
{
<span class="alert-info">@TempData["Emails"]</span>
}

控制器:

    [HttpPost]
    public ActionResult Customers(int[] ids)
    {
        Customers cu= new Customers();
        cu.IDS = ids;
        cu.GetEmails(ids);
        TempData["ids"] = string.Join(",", ids.ToArray());
        TempData["Emails"] = cu.GetEmails(ids).Email.ToArray(); // I want these emails in my view
        return RedirectToAction("Customers");
    }

型号:

public Customers GetEmails(int[] ids)
    {
        Customers ee = new Customers();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mvc"].ConnectionString);
        string qry = "select Email from users where Id IN(" + string.Join(",", ids.ToArray()) + ")"; 
        SqlCommand cmdd = new SqlCommand(qry, con);
        con.Open();
        SqlDataReader rdd = cmdd.ExecuteReader();
        while (rdd.Read())
        {
          ee.Email = rdd["Email"].ToString();  // I am able to get all emails
        }
        rdd.Close();
        cmdd.ExecuteNonQuery();
        con.Close();
        return ee;
    }

1 个答案:

答案 0 :(得分:2)

让我们从一些虚拟数据和测试用例场景开始

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

    [HttpPost]
    public ActionResult Test(MyModel model)
    {
        TempData["test"] = GetData();
        return View();
    }

    public List<string> GetData() //method for get data
    {
        List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
        return mylist;
    }

和剃刀视图

var data = TempData["test"] as List<string>;
if (data != null)
{
    foreach (var a in data)
    {
        W‌riteLiteral(@"<li>"); /*​*/
        W‌rite(a); /*​*/
        W‌riteLiteral(@"</li>");
    }
}

现在,在您的情况下,我假设您的GetEmail仅返回一组字符串,因此将您的返回类型更改为list<string>,将Customer对象的返回类型更改为public List<string> GetEmails()并返回ee。字符串列表。

然后您需要在剃刀视图中做的所有事情,例如测试用例场景。