How to change DropdownList to editable textbox when EDIT button is clicked in MVC ...?

I need to change my dropdown to an editable textbox by clicking the Edit button. Here I have a Dropdownlist in my CSHTML file and when I select a value in DDL, the textbox fills in the corresponding value from the table.

here is my model

This Plan_S model class is autogenerated by VS when I connect a table from the database to MVC using ADO.NET Entity

public partial class Plan_S
    {
        public int PlanId_PK { get; set; }
        public string PlanNames { get; set; }
        public string Hours { get; set; }
        public string PlanCost{ get; set;}

      

public}

This class is created to enumerate the Plan_S class

public class PlanViewModel
    {

        public List<SelectListItem> Plans { get; set; }        
    }

      

My controller

public class dropdownController : Controller
    {


        private PivotEntities db = new PivotEntities();

        //
        // GET: /dropdown/

        public ActionResult Index()
        {
            var model = new PlanViewModel();

            //model.Plan = CurrentPlan; //Replace this with the current plan you're editing
            model.Plans = db.Plan_S
                .Select(p => new SelectListItem
                {

                    Value = p.Hours,                   
                    Text = p.PlanNames

                })
                .ToList();

            return View(model);
        }
protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
}

      

My View file for displaying the dropdown list, TextBox, Edit and Save buttons.

@model Pivot.Models.PlanViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<table>

    <tr id="ddl">

        <td>@Html.Label("Select Plan : ") </td>
        <td>@Html.DropDownList("PlanNames", Model.Plans, "--select--") </td>

    </tr>
    <tr id="editplan">
        <td>@Html.Label("Edit Plan : ")</td>
        <td><input id="plannames" type="text" /></td>        
    </tr>
    <tr>
        <td>@Html.Label("Hours  :")</td>
        <td><input id="planHours" type="text" /></td>        
    </tr>
    <tr>
        <td>@Html.Label("Edit  :")</td>
        <td><input id="Button1" type="button" value="Edit" /></td>
    </tr>
    <tr>
        <td>@Html.Label("Save Changes :")</td>
        <td><input id="savebutton" type="submit" value="Save" /></td>        
    </tr>
</table>




<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery.js"></script>
<script type="text/javascript">
    $(function () {
        $("[name='PlanNames']").change(function () {
            $("#planHours").val($(this).val());
        });
        $("#plannames").val($(this).val(""));
    });
    $(document).ready(function () {
        $("#editplan").hide();
        $("#Button1").click(function () {
            $("#ddl").hide();
            $("#editplan").show();
        });
        $("#savebutton").click(function () {
            $("#editplan").hide();
            $("#ddl").show();
        });


    });
</script>

      

My Table Plan_S looks like this:

  PlanId_PK   |    PlanNames    |     Hours     |      PlanCost

      1              Plan1             1hrs              $10
      2              Plan2             2hrs              $20
      3              Plan3             3hrs              $30

      

This is where I need it when you select the dropdownlist from PlanNmes.

ie,) when choosing Plan2 in DDL, there are two text boxes, each of which must be filled with a corresponding value from Hours, and another text box must be filled from PlanCost.

When I click the Edit button, the dropdown and the other two text boxes should be converted to editable text boxes, and after that I have to edit the plan, plnacost, hours and then when I click the save button it should be saved to Plan_S.

I am trying to use this with JQuery ...

Since I am new to MVC I am confused ......

Please advise me that ......

Thanks in Advance .... :)

+1


source to share


1 answer


This requires quite a lot of ajax messing around. Hope you get the idea.

I would just populate the SelectListItems dropdown where Value is the primary key of Plan_S as usual. This allows the code to scale if your Plan_S expands and you need additional edit fields:

model.Plans = db.Plan_S
            .Select(p => new SelectListItem
            {

                Value = p.PlanId_PK,                   
                Text = p.PlanNames

            })
            .ToList();

      

In the html add a hidden field for the ID so we know which plan we are currently editing. We also need to keep the plancost so that it is not null on update. Note that I am also using a class to hide plan fields, so we have the correct markup when hiding multiple lines:

<tr id="ddl">
    <td>Select plan</td>
    <td>@Html.DropDownList("PlanNames", Model.Plans, "--select--") </td>
</tr>
<tr class="editplanfield">

    <td>@Html.Label("Edit Plan : ")</td>
    <td><input id="plannames" type="text" />
        <input type="hidden" id="planid"/>
        <input type="hidden" id="plancost"/>
    </td>        
</tr>
<tr class="editplanfield">
    <td>@Html.Label("Hours  :")</td>
    <td><input id="planHours" type="text" /></td>        
</tr>
<tr>
    <td>@Html.Label("Edit  :")</td>
    <td><input id="editbutton" type="button" value="Edit" /></td>
</tr>
<tr>
    <td>@Html.Label("Save Changes :")</td>
    <td><input id="savebutton" type="submit" value="Save" /></td>        
</tr>

      

Then, in the editbutton window, we request the selected plan from the server and fill in the edit fields:



$("#editbutton").click(function () {
        $("#ddl").hide();
        $(".editplanfield").show();
        // Request plan of selected id from server
        $.getJSON('@Url.Action("GetPlan")', { planId: $("[name='PlanNames']").val() }, function (plan) {
            // Fill the fields according to the Jsondata we requested
            $("#planid").val(plan["PlanId_PK"]); 
            $("#plannames").val(plan["PlanNames"]);
            $("#planHours").val(plan["Hours"]);
            $("#plancost").val(plan["PlanCost"]);
            });
    });

      

Here is the server side controller code for the request:

    public JsonResult GetPlan(int planId)
    {
        var plan = db.Plan_S.Find(planId);
        return Json(plan, JsonRequestBehavior.AllowGet);
    }

      

Now we need to save the changes without postbacks, so we need more ajax:

$("#savebutton").click(function () {
        // Parse the plan from fields
        var plan = new Object();
        plan.PlanId_PK = $("#planid").val();
        plan.PlanNames = $("#plannames").val();
        plan.Hours = $("#planHours").val();
        plan.PlanCost = $("#plancost").val()
        // Post it to server
        $.ajax({
            type: "POST", url: "@Url.Action("UpdatePlan")",
            success: function (result)
            {
                //Postback success
                $(".editplanfield").hide();
                $("#ddl").show();
            },
            data: plan,
            accept: 'application/json'
        });
    });

      

Then, on the backend server, we need an action to update the plan:

    [HttpPost]
    public JsonResult UpdatePlan(Plan_S plan)
    {
        /*  Update the plan in database */
        /* Just return something for now */
        return Json("Success");
    }

      

+1


source







All Articles