Mohammad
Mohammad

Reputation: 1577

how to pass checkbox value to controller on form submit then return data to view?

In My view i placed a check box in-front of some user records .when I check a check box and click on submit button then the selected checkbox values (user Id) will be sent to controller. currently i successfully get emails in my model but can't get the DB result back in view.

Customers View :

@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>
}

Controller :

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

Model :

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;
    }

Upvotes: 0

Views: 310

Answers (1)

Ziaul Kabir Fahad
Ziaul Kabir Fahad

Reputation: 230

Well lets start with some dummy data and test case scenario

 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;
    }

and razor view

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

Now with your scenario I assume that your GetEmail only return a set of string so change your return type to Customer object to list<string> as public List<string> GetEmails() and return ee as list of string.

Then all you need to do in your razor view like test case scenario.

Upvotes: 2

Related Questions