0

Form

I have a form as above. I am trying to work as when user selects Table Name & Permission, it goes back to server side, fetches the columns of the selected table & display all column names as check boxes. When use selects Save btn, HttpPost will execute and when user selects Cancel, to return back to home page.

I have created a ViewModel for this :

 // Actual EF Model
    public partial class TablePermission
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int PermissionLevelId { get; set; }
    public string TableName { get; set; }
    public string RestrictViewFields { get; set; }
    public string RestrictEditFields { get; set; }

    public virtual PermissionLevel PermissionLevel { get; set; }
    public virtual User User { get; set; }
}
// View Model for the View
public class TablePermissionsVM
{

    public TablePermissionsVM()
    {
        TablePermission = new TablePermission();
        RestrictViewFields = new List<FieldList>();

        // Created for trial to see Checkboxes 
        RestrictViewFields.Add(new FieldList() { FieldName = "UserId", Selected = false });
        RestrictViewFields.Add(new FieldList() { FieldName = "fName", Selected = false });
        RestrictViewFields.Add(new FieldList() { FieldName = "lName", Selected = false });

        RestrictEditFields = new List<FieldList>();
    }

    public TablePermission TablePermission { get; set; }

    public List<FieldList> RestrictViewFields { get; set; }

    public IEnumerable<FieldList> RestrictEditFields { get; set; }
}

// Model to save field names & it's selected status
public class FieldList
{
    public string FieldName { get; set;  }
    public bool Selected { get; set; }
}
}

Controller UPDATED : ADDED THE NEW ACTION (FillFields() ) METHOD that has to called onChange event

       [Authorize]
    [HttpGet]
    public ActionResult TablePermissions(TablePermissionsVM tablePermissionVm)
    {
        return View(tablePermissionVm);
    }

    // Action Method to Fill Column names for the List<>.
    public ActionResult FillFields(string tableName, string tblPermLevel)
    {
        // WANT TO RETURN HERE ANOTHER LIST (2 LIST OBJECTS) IN JSON
        // restrictView & restrictEdit 
        var restrictView = DbUtilities.GetColumnNames(tableName);
        var restrictEdit = DbUtilities.GetColumnNames(tableName);
        return Json(restrictView, JsonRequestBehavior.AllowGet);
    }

View - UPDATED CODE : aDDED Bound fields for TableName & TableLevelPermission, Script that I use on the event of change of Table Selected. UPDATED - aDDED FORM ID, SCRIPT METHOD

       @model DataStudio.Models.TablePermissionsVM

using (Html.BeginForm("TablePermissions", "Admin", FormMethod.Post, new { id = "tblPermForm" }) ))
{
    @Html.AntiForgeryToken()

        <div class="form-group">
            @Html.LabelFor(model => model.TablePermission.TableName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="editor-field">
                @Html.DropDownListFor(model => model.TablePermission.TableName, 
                    DbUtilities.GetTableNames(), "Select Table", 
                    new { @class = "form-control", @onchange="FillFields()" })
                @Html.ValidationMessageFor(model => model.TablePermission.TableName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TablePermission.PermissionLevelId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="editor-field">
                @Html.DropDownListFor(model => model.TablePermission.PermissionLevelId, DbUtilities.GetPermissionLevelList(), "Select Permission Level", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.TablePermission.PermissionLevelId, "", new { @class = "text-danger" })
            </div>
        </div>

       <div class="form-group">
            @Html.LabelFor(model => model.RestrictViewFields, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="editor-field">
                 **// NEED TO ADD CHECK BOXES HER RECEIVED THRU SCRIPT** 
            </div>
        </div>
  }

<script>
    function FillFields() {
        var tblName = $('#TablePermission_TableName').val();
        var tblPermLevel = $('#TablePermission_PermissionLevelId').val();

        //($('tblPermForm').valid()) { ERROR - OBJECT DOESN'T HAVE valid()'
        if (tblName != null && tblPermLevel != null) {
            $.ajax({
                url: '/Admin/FillFields',
                type: 'GET',
                dataType: "JSON",
                data: { TableName: tblName, TablePermLevel: tblPermLevel },
                success: function (restrictView) {
                    $("#RestrictViewFields").html("");  // Clear before appending new ones
                    $.each(restrictView, function (i, field) {
                        $("#RestrictViewFields").append(
                            $('<option></option>').val(field.FieldName).html(field.FieldName))  
                  // WANT TO ADD AS 3 CHECKBOX IN A ROW
                    });

                }
            });
        }
    }
  </script>

Their are couple of things that I am not able to figure out & get confused with it. Mainly, on making sure that both the drop down boxes has value, I need to perform again a "Get" and fetch column names for the table selected & display the columns as check boxes. The way I have implemented Checkboxes, I will get proper selected Values in HttpPost, Right ! Are am I anywhere wrong ?

How to make the Get Request when both the drop down's are selected ??

Any help is highly appreciated. Thanks a lot in advance.

Update I started to try with only TableName selection (I want for both dropdown), but the event doesn't occur and go to FillFields() in script. Where am I going wrong ? I tried this logic from here . Can't get why it doesn't get fired only ??? Btw, this is a full form i mean, their is no partial form in it. I want to fill the check box controls in those 2 RestrictXFields on selection of TableName & Permssion check box & on Save btn, send all to Request & save to db.

UPDATE : THANKS a lot, Stephen & Chethan. With your support, I identified the cause for event not getting triggered. Event is triggered, I am able to retrieve the column names from db, the HTML part on success is not being updated. Stephen, I also added form Id & tried form.valid() as you instructed, but I get error script doesn't identify valid(). Both the fields in Model are marked as Required in MetaData class. Currently, testing both var != null works. But, I liked you valid() option.

15
  • Why make another round trip by posting just the value of the <select>'s? You can use ajax to call a server method that returns your checkboxes based on the selection and update the DOM Commented Jul 25, 2017 at 22:44
  • 1
    verfiy if your script is actually rendered on the page? and check the TableName dropdown markup in browser. Commented Jul 26, 2017 at 1:11
  • 1
    And you do not have an element with id="TableName" (if you want the value of the <select> it would be $('#TablePermission_TableName').val() Commented Jul 26, 2017 at 1:37
  • 1
    Inspect the html your code is generating to see the id attribute :) Commented Jul 26, 2017 at 1:46
  • 1
    You just need to first check that both are not null e.g. if (tblName && yourOtherVariable){ make ajax call }; but it would be far better to have your properties decorated with the [Required] attributes so that you can first check if the form is valid - e.g. if ($('form').valid() { make ajax call } so that you valdation errors are displayed Commented Jul 26, 2017 at 2:07

1 Answer 1

1

Per my understanding, You should fetch the checkboxes using an ajax call.

Create an action method in your controller which accepts selected values of TableName and TableLevelPermisson dropdown. Use these values to fetch

List<FieldList> RestrictViewFields  
IEnumerable<FieldList> RestrictEditFields. 

and use as data/model to your partial view.

Call this action method using ajax, on change of the dropdown list value. Get the HTML returned from partial view and use it in your DOM.

How to make the Get Request when both the drop down's are selected ??

If you are using jQuery: Just google for "dropdown change events in jquery" and ajax call examples.

Sign up to request clarification or add additional context in comments.

3 Comments

the drop down values of TableName & TableLevelPermission are already associated with model.TablePermission.TableName & model.TablePermission.TableLevelPermission respectively. I have updated my question & added some code that I have tried with ajax call, but it doesn't work. Can you please look at it and help me know where am I going wrong ! Thanks
Can you show me what HTML this line is producing: @Html.DropDownListFor(model => model.TablePermission.TableName, DbUtilities.GetTableNames(), "Select Table", new { @class = "form-control", @onchange="FillFields()" }) ?? (Inspect element in browser): should show something like this: <select class="form-control" id="TablePermission.TableName" name="TablePermission.TableName" onchange="FillFields()"> <option value="1">Name1</option> <option value="1">Name1</option>... </select>
<select name="TablePermission.TableName" class="form-control" id="TablePermission_TableName" onchange="FillFields()" data-val-required="Select Table Name to set Permission for User " data-val="true"><option value="">Select Table</option> <option value="[dbo].[Permission]">Permission</option> <option value="[dbo].[PermissionLevel]">PermissionLevel</option> <option value="[dbo].[Role]">Role</option> <option value="[dbo].[User]">User</option> <option value="[dbo].[UserRoles]">UserRoles</option> <option value="[dbo].[TablePermission]">TablePermission</option> </select>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.