lundi 26 juin 2017

How to send SQL Server table Id from View to Controller in MVC? I'm making a checkbox functionality to delete multiple rows from table

I'm trying to make a checkbox functionality to delete multiple rows with click of single button. It seems that the checkbox can pick up the Table Id, but can't send it back to controller. Any idea about how to achieve this?

My code: This is the partial view. I'm trying to sent the data from here to the controller.

@model IEnumerable<SecondTable>

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />

<br />
<br />

<!-------------Code to display second table------------------->

<div>
        <table border="1" align="center" class="table table-bordered table-hover table-condensed text-center">
            <tr><td><b>Table 2</b></td></tr>

                   @{
                       foreach (var item in Model)
                       {
                          <tr><td>@item.name</td></tr>
                       }
                    }


        </table>
    </div>

<!--------Code to execute deletion of data from table------------------>

<script type="text/javascript">
    function def()
    {
        $.ajax
            ({
            url: "/Home/DeleteData",
            type: "get",
            dataType: "html",
            data: { a: $("#name").val() },
            success: function (data) {
                $("#table3").html(data);
            }
            });
    }
</script>

<!----------Delete Button defined (can only delete one row)---------------->

    <div class="text-center">
        <br />
        <input type="button" value="Delete Data" onclick="def()" class="btn btn-danger" />
        <br />
    </div>

    <!--------------------------Delete Multiple Rows------------------->
    <div id="newdiv">
               <table border="1" id="table2" align="center" class="table table-bordered table-hover table-condensed text-center">
                <tr><th colspan="2" class="text-center">Table 2</th></tr>

                       @{
                           foreach (var item in Model)
                           {
                              <tr>  
                                 <td><input type="checkbox" name="Delete" id="Delete" value="@item.id" /></td>                             
                                 <td>@item.name</td>                                                                           
                              </tr>                     
                           }

                        }
                     <tbody>
                         @Html.EditorForModel()
                     </tbody>       

            </table>
         </div>

Index View (I don't think Index View one is relevant to the question,but I'm still mentioning the code):

@model IEnumerable<MovingApplication.Models.Class1>

@{
    Layout = null;
    ViewBag.message = "hello world";
}

<div class="jumbotron" style="background:#E74C3C !important" >
<h2 style="text-align:center">Table Data</h2></div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="http://ift.tt/2nYZfvi"></script>

<!---------------------Table 1 Defined--------------------------------->
<div id="table2">
    <table id="tableA" border="1" align="center"
           class="table tableA table-bordered table-hover 
           table-condensed table-layout: fixed text-center">
        <tr><th colspan="1" class="text-center">Table 1</th></tr>

         @{foreach (var item in ViewBag.userdetails)
                   {
                 <tr><td width="10%">@item.name</td></tr>
                }}

             }
    </table>
</div>
<div id="table3">
</div>

<!-------To delete multiple rows----->
<script type="text/javascript">
    function deleteMultipleRows(){
        var id=[];
        $("#table2 input[type=checkbox]").each(function(){
        {
            if($(this).is(":checked"))
            {
                id.push($(this).attr("id"));
            }
        }
    });
    alert(id);
    $.ajax({
        url:"/Home/Delete",
        type:"get",
        datatype:"html",
        data:{id: id.toString()},
        success: function(data){
            $("#newdiv").empty();
            $("#newdiv").html(data);
        }
    })

}
</script>

<!------------Autocomplete Text Sent to MoveData Method-------------------->

<script type="text/javascript">
    function abc() {
        $.ajax({
            url: "/Home/MoveData",
            type: "get",
            dataType: "html",
            data: { a: $("#name").val() },
            success: function (data) {
             $("#table3").html(data);
            }

        });

    }
</script>

<!--------------Code to show contents of Table 2------------------->


<script type="text/javascript">
    function def()
    {
        $("#btn").hide();      
        $.ajax
            ({
            url: "/Home/ShowData",
            type: "get",
            dataType: "html",
            data: { a: $("#name").val() },
            success: function (data) {
                $("#table3").html(data);
             }
            });
    }
    </script>


<!------------------Code to load autocomplete list---------------------->



<script type="text/javascript">

    $(document).ready(function () {
        $("#name").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.name };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>

<!----------------------------Input Field--------------------------------->

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div id="button1">
        <hr />
        <div >
            <div class="text-center" >
                <p><b>Enter Any Data</b></p>
                <div class="col-lg-4 col-lg-offset-4">                   
                    @Html.Editor("name", new { htmlAttributes = new { @class = "form-control text-mywidth" } })
                </div>
            </div>

            <div class="text-center col-lg-4 col-lg-offset-4"><br />
                <input type="button" style="grid-row-align:start" value="Move/Add" onclick="abc()" class="btn btn-success" />
                <input type="button" style="align-self:auto" value="Show Table 2" id="btn" onclick="def()" class="btn btn-info" />

            </div>
        </div>
    </div>
    <br />

    /*-------------Buttons defined to Add/Move/Show data--------------*/
}

HomeController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using MovingApplication.Models;

namespace MovingApplication.Controllers
{
    public class HomeController : Controller
    {
        MoveDBEntities db = new MoveDBEntities();

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(Login log)
        {
            var user = db.loginTables.Where(x => x.email == log.email && x.password == log.password).FirstOrDefault();

            if (user != null)
            {
              return RedirectToAction("Index");
            }
            else
            {
                ViewBag.message = "Invalid Username or Password";
            }
            return View();
        }

        [HttpGet]
        public ActionResult Index()
        {           
           var data = db.FirstTables.ToList();
           ViewBag.userdetails = data;
           return View();
        }

        [HttpPost]
        public ActionResult Index(string Prefix)
        {

            var tempstring = (from N in db.FirstTables
                              where N.name.StartsWith(Prefix)
                              select new { N.name }).ToList();

            List<Autocomplete> obj = new List<Autocomplete>();
            foreach (var item in tempstring)
            {
                obj.Add(new Autocomplete() { name = item.name });
            }
            return Json(obj, JsonRequestBehavior.AllowGet);
        }



          public PartialViewResult MoveData(string a)
        {
            FirstTable data = db.FirstTables.Where(x => x.name == a).FirstOrDefault();
            if (data != null)
            {
                var result = db.FirstTables.Remove(data);
                db.SaveChanges();
            }
            SecondTable t2 = new SecondTable();
            t2.name = a;
            db.SecondTables.Add(t2);
            db.SaveChanges();
            ViewBag.userdetails2 = db.SecondTables.ToList();
            List<SecondTable> randomList = db.SecondTables.ToList();
            ViewBag.userdetails3 = randomList;

            return PartialView("_PartialViewX", randomList);
        }

        public PartialViewResult ShowData()
        {
            SecondTable t2 = new SecondTable();
            ViewBag.userdetails2 = db.SecondTables.ToList();
            List<SecondTable> randomList = db.SecondTables.ToList();
            ViewBag.userdetails3 = randomList;

            return PartialView("_PartialViewX", randomList);
            //return Json(data2,JsonRequestBehavior.AllowGet);

        }

        public PartialViewResult DeleteData(string a)
        {
            SecondTable data = db.SecondTables.Where(x => x.name == a).FirstOrDefault();
            if (data != null)
            {
                var result = db.SecondTables.Remove(data);
                db.SaveChanges();
            }

            ViewBag.userdetails2 = db.SecondTables.ToList();
            List<SecondTable> randomList = db.SecondTables.ToList();
            ViewBag.userdetails3 = randomList;

            return PartialView("_PartialViewX", randomList);

        }

      [HttpPost]

             public ActionResult Delete(IEnumerable<int> delids)
        {
            if (delids != null)
            {
                foreach (var id in delids)
                {
                    var randomness = db.SecondTables.Single(s => s.id == id);

                    if (randomness != null)
                    {
                        db.SecondTables.Remove(randomness);
                    }
                    db.SaveChanges();
                }
            }
            return RedirectToAction("Index");
        }

         public class Autocomplete
        {
            public string name { get; set; }
        }
    }
}

Class1(Model):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MovingApplication.Models
{
    public class Class1
    {
        public int id { get; set; }
        public string name { get; set; }
    }

}




Aucun commentaire:

Enregistrer un commentaire