Friday, January 15, 2016

Multiple submit buttons in .NET MVC, Handle more than one button. Working tested 100%


  1. CASE (name attribute name should be same name as parameter in ActionResult method)
View (model) code--------------------------
@{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_LayoutAsh.cshtml";
}

<h2>Welcome to Home page with this master page</h2>

@using (Html.BeginForm("MultipleButton", "Home", FormMethod.Post))
{

@Html.TextBox("My")
<input type="submit" name="ASH" value="Save" />
<input type="submit" name="ASH" value="Update" />
<input type="submit" name="ASH" value="Delete" />
   
}
@ViewData["save"]

Controller (model) code--------------------------
public ActionResult ButtonForm()
        {           
            return View("Home");
        }
        public ActionResult MultipleButton(string ASH)
        {
            if (ASH == "Save")
            {
                ViewData["save"] = "save clicked";
            }
            if (ASH == "Update")
            {
                ViewData["save"] = "update clicked";
            }
            if (ASH == "Delete")
            {
                ViewData["save"] = "Delte clicked";
            }
            return View("Home");
        }
       

  1. CASE 2
View (model) code--------------------------

@{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_LayoutAsh.cshtml";
}

<h2>Welcome to Home page with this master page</h2>

@using (Html.BeginForm("MultipleButton", "Home", FormMethod.Post))
{

@Html.TextBox("My")

<input type="submit" name="button1" value="Save" />
<input type="submit" name="button2" value="Update" />
<input type="submit" name="button3" value="Delete" />
   
}
@ViewData["save"]


 Controller (model) code--------------------------


        public ActionResult ButtonForm()
        {           
            return View("Home");
        }

        public ActionResult MultipleButton()
        {
            if (Request.Form["button1"] == "Save")
            {
                ViewData["save"] = "save clicked";
            }
            if (Request.Form["button2"] == "Update")
            {
                ViewData["save"] = "update clicked";
            }
            if (Request.Form["button3"] == "Delete")
            {
                ViewData["save"] = "Delte clicked";
            }
            return View("Home");
        }

Thursday, January 14, 2016

MVC .net insert update delete select/view in single view by JSON jquery

MVC .net insert update delete select/view in single view by JSON jquery and entity data model.

Here i have created a testMVC applicaiton and faced problem with auto generated too many view with entity framework. So every database operation i handled in the same view(controller). 

code written in the view
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutAsh.cshtml";
}
<h2>
    Jquery example.</h2>
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

<script type="text/javascript">
    function ViewAll() {
        ///////////  Fetch all Method   /////////////
        $('#tblProducts tbody').html('');
            $.ajax(
            {
                type: 'POST',
                url: 'jqury/GetAllData',
                dataType: 'json',
                data: { id: 'ash' },
                success: function (ashdata) {
                    var items = '';
                    $.each(ashdata, function (i, item) {

                        var rows = "<tr>"
                                    + "<td class='prtoducttd'>" + item.ProductID + "</td>"
                                    + "<td class='prtoducttd'>" + item.ProductName + "</td>"
                                    + "<td class='prtoducttd'>" + item.QuantityPerUnit + "</td>"
                                    + "<td class='prtoducttd'>" + item.UnitPrice + "</td>"
                                    + "<td class='prtoducttd'>" + item.UnitsInStock + "</td>"
                                    + "<td class='prtoducttd'>" + item.ReorderLevel + "</td>"
                                    + "<td class='prtoducttd'><a href='#' onclick='GetDataEdit(" + item.ProductID +
                                    ");'>Edit</a> | <a href='#' onclick='Delete(" + item.ProductID + ");' title='" + item.ProductID + "'>Delete</a></td>"
                                    + "</tr>";
                        $('#tblProducts tbody').append(rows);
                    });

                }
             });
        }
        $(document).ready(function () {
            ViewAll();
        });

        ///////////  Save Method   /////////////
        function SaveNew() {
            if ($("#Save").text() == "Update") {
                UpdateEdit($("#pid").val());
            }
            else {
                $.ajax(
                    {
                        type: 'POST',
                        url: 'jqury/SaveNew',
                        data: {
                            ProName: $("#ProName").val(),
                            Qty: $("#Qty").val(),
                            UnitPrice: $("#UnitPrice").val(),
                            UnitStock: $("#UnitStock").val(),
                            Reorder: $("#Reorder").val()

                        },
                        success: function (data) {
                            alert('saved successfully.');
                            ViewAll();
                        }
                    });
            }
        }

        ///////////  Delete Method   /////////////
        function Delete(id) {
            $.ajax(
            {
                type: 'POST',
                url: 'jqury/DeleteById',
                data: {
                    proid: id
                },
                success: function (data) {
                    alert('Deleted successfully.');
                    ViewAll();
                }
            });
        }

        ///////////  Update Function ////////////
        function UpdateEdit(id) {
            $.ajax(
            {
                type: 'POST',
                url: 'jqury/UpdateEdit',
                data: {
                    proid: id,
                    ProName: $("#ProName").val(),
                    Qty: $("#Qty").val(),
                    UnitPrice: $("#UnitPrice").val(),
                    UnitStock: $("#UnitStock").val(),
                    Reorder: $("#Reorder").val()
                },
                success: function (data) {
                    alert('Updated successfully.');
                    ViewAll();
                }
            });
        }

        ///////////  Fetch to textbox method   /////////////
        function GetDataEdit(pid) {
            $.ajax(
            {
                type: 'POST',
                url: 'jqury/GetDataById',
                dataType: 'json',
                data: { proid: pid },
                success: function (ashdata) {
                    $("#ProName").val(ashdata.ProductName),
                    $("#Qty").val(ashdata.QuantityPerUnit),
                    $("#UnitPrice").val(ashdata.UnitPrice),
                    $("#UnitStock").val(ashdata.UnitsInStock),
                    $("#Reorder").val(ashdata.ReorderLevel),
                    $("#pid").val(ashdata.ProductID)
                    $("#Save").text('Update');
                }
            });
        }
</script>
<table>
@Html.Hidden("pid")
<tr><td>ProductName : </td><td>@Html.TextBox("ProName")</td></tr>
<tr><td>QuantityPerUnit : </td><td>@Html.TextBox("Qty")</td></tr>
<tr><td>UnitPrice : </td><td>@Html.TextBox("UnitPrice")</td></tr>
<tr><td>UnitsInStock : </td><td>@Html.TextBox("UnitStock")</td></tr>
<tr><td>ReorderLevel : </td><td>@Html.TextBox("Reorder")</td></tr>
<tr><td></td><td><a href="#" id="Save" onclick="SaveNew();">Save</a></td></tr>
</table>
---------------------------------------------------------------------------------------
<table id="tblProducts" class="tblProducts">
    <thead>
        <tr>
            <th align="left" class="productth">
                ProductID
            </th>
            <th align="left" class="productth">
                ProductName
            </th>
            <th align="left" class="productth">
                QuantityPerUnit
            </th>
            <th align="left" class="productth">
                UnitPrice
            </th>
            <th align="left" class="productth">
                UnitsInStock
            </th>
            <th align="left" class="productth">
                ReorderLevel
            </th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>


<style type="text/css">
    .tblProducts {
        font-family: verdana,arial,sans-serif;
        font-size: 11px;
        color: #333333;
        border-width: 1px;
        border-color: #666666;
        border-collapse: collapse;
    }

    .productth {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #dedede;
    }

    .prtoducttd {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #ffffff;
    }
</style>


 ///////////////////////////////
Code in the controller---------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestDAL;

namespace MVCTest.Controllers
{
    public class JquryController : Controller
    {
        //
        // GET: /Jqury/
        GaneshaEntities ge = new GaneshaEntities();
        public ActionResult Index()
        {
            List<ProductMaster> pm = ge.ProductMasters.ToList();           
            return View();
        }

        public JsonResult GetAllData()
        {
            List<ProductMaster> pm = ge.ProductMasters.ToList();
            return Json(pm, JsonRequestBehavior.AllowGet);
        }

        public void SaveNew(string ProName, string Qty, string UnitPrice, string UnitStock, string Reorder)
        {
            ProductMaster pm = new ProductMaster();
            pm.ProductName = ProName;
            pm.QuantityPerUnit = Qty;
            pm.UnitPrice = UnitPrice;
            pm.UnitsInStock = UnitStock;
            pm.ReorderLevel = Reorder;
            ge.ProductMasters.AddObject(pm);
            ge.SaveChanges();
        }

        public void DeleteById(int proid)
        {
            ProductMaster pro = ge.ProductMasters.First(x => x.ProductID == proid);
            ge.ProductMasters.DeleteObject(pro);
            ge.SaveChanges();
        }

        public void UpdateEdit(int proid, string ProName, string Qty, string UnitPrice, string UnitStock, string Reorder)
        {
            ProductMaster pro = ge.ProductMasters.First(x => x.ProductID == proid);
            pro.ProductName = ProName;
            pro.QuantityPerUnit = Qty;
            pro.UnitPrice = UnitPrice;
            pro.UnitsInStock = UnitStock;
            pro.ReorderLevel = Reorder;
            ge.SaveChanges();
        }

        public JsonResult GetDataById(int proid)
        {
            ProductMaster pro = ge.ProductMasters.First(x => x.ProductID == proid);
            return Json(pro, JsonRequestBehavior.AllowGet);
        }
    }
}