2

I have a strongly typed view in which I am looping over some objects from a database and dispaying them in a jumbobox with two buttons in it. When I click one of the buttons I have a modal popping up. I'd like to have somewhere in this modal the name and the id of the corresponding object, but I do not really know how to do this. I am a bit confused where to use c# and where javascript. I am a novice in this, obviously.

Can someone help?

This is the code I have so far. I don't have anything in relation to my question, except the code for the modal :

 @model IEnumerable<eksp.Models.WorkRole>
@{
    ViewBag.Title = "DisplayListOfRolesUser";
}

<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var dataJSON;
        $(".alert").hide();
        //make the script run cuntinuosuly
        $.ajax({
            type: "POST",
            url: '@Url.Action("checkNumRoles", "WorkRoles")',
            dataType: "json",
            success: successFunc,
            error: errorFunc
        });

        function successFunc(data, status) {


            if (data == false) {
                $(".alert").show();
                $('.btn').addClass('disabled');

                //$(".btn").prop('disabled', true);
            }

        }

        function errorFunc() {
            alert('error');
        }


    });


</script>



@foreach (var item in Model)
{

    <div class="jumbotron">
        <h1>@Html.DisplayFor(modelItem => item.RoleName)</h1>
        <p class="lead">@Html.DisplayFor(modelItem => item.RoleDescription)</p>
        <p> @Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { @class = "btn btn-primary btn-lg" })</p>
        <p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
    </div>

}



<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">@Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
            </div>
            <div class="modal-body">
                <p>Some text in the modal.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
            </div>
        </div>

    </div>
</div>
Robert Ross
  • 1,151
  • 2
  • 19
  • 47

2 Answers2

2

I think your confusing the server side rendering of Razor and the client side rendering of the Modal. The modal cannot access your Model properties as these are rendered server side before providing the page to the user. This is why in your code <h4 class="modal-title">@Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4> this does not work.

What you want to do is capture the event client side in the browser. Bootstrap allows you to achieve this by allowing you to hook into events of the Modal. What you want to do is hook into the "show" event and in that event capture the data you want from your page and supply that to the Modal. In the "show" event, you have access to the relatedTarget - which is the button that called the modal.

I would go one step further and make things easier by adding what data you need to the button itself as data-xxxx attributes or to DOM elements that can be easily access via JQuery. I have created a sample for you based on what you have shown to give you an idea of how it can be achieved.

Bootply Sample

And if needed... How to specify data attributes in razor

Community
  • 1
  • 1
Judge Bread
  • 501
  • 1
  • 4
  • 13
1

First of all

you will need to remove the data-toggle="modal" and data-target="#myModal" from the button, as we will call it manually from JS and add a class to reference this button later, your final button will be this:

<button type="button" class="btn btn-default btn-lg modal-opener">Had role in the past</button>

Then

In your jumbotron loop, we need to catch the values you want to show later on your modal, we don't want to show it, so we go with hidden inputs:

<input type="hidden" name="ID_OF_MODEL" value="@item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="@item.RoleName" />

For each information you want to show, you create an input referencing the current loop values.

Now you finally show the modal

Your document.ready function will have this new function:

$('.modal-opener').on('click', function(){
      var parent = $(this).closest('.jumbotron');
      var name = parent.find('input[name="NAME_OF_MODEL"]').val();
      var id = parent.find('input[name="ID_OF_MODEL"]').val();

      var titleLocation = $('#myModal').find('.modal-title');
      titleLocation.text(name);

      // for each information you'll have to do like above...

      $('#myModal').modal('show');
});

It simply grab those values we placed in hidden inputs.

Your final code

@model IEnumerable<eksp.Models.WorkRole>
@{
     ViewBag.Title = "DisplayListOfRolesUser";
 }

 <div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script type="text/javascript">
  $(document).ready(function () {
       var dataJSON;
       $(".alert").hide();
       //make the script run cuntinuosuly
       $.ajax({
          type: "POST",
          url: '@Url.Action("checkNumRoles", "WorkRoles")',
          dataType: "json",
          success: successFunc,
          error: errorFunc
    });

    function successFunc(data, status) {


        if (data == false) {
            $(".alert").show();
            $('.btn').addClass('disabled');

            //$(".btn").prop('disabled', true);
        }

    }

    function errorFunc() {
        alert('error');
    }

    $('.modal-opener').on('click', function(){
       var parent = $(this).closest('.jumbotron');
       var name = parent.find('input[name="NAME_OF_MODEL"]').val();
       var id = parent.find('input[name="ID_OF_MODEL"]').val();

       var titleLocation = $('#myModal').find('.modal-title');
       titleLocation.text(name);

       // for each information you'll have to do like above...

       $('#myModal').modal('show');
     });
});


</script>



@foreach (var item in Model)
{

    <div class="jumbotron">
    <input type="hidden" name="ID_OF_MODEL" value="@item.WorkRoleId" />
    <input type="hidden" name="NAME_OF_MODEL" value="@item.RoleName" />

    <h1>@Html.DisplayFor(modelItem => item.RoleName)</h1>
    <p class="lead">@Html.DisplayFor(modelItem => item.RoleDescription)</p>
    <p> @Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { @class = "btn btn-primary btn-lg" })</p>
    <p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>

}



<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">@Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
        </div>
        <div class="modal-body">
            <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
        </div>
    </div>
</div>

  • i am referring to the WorkRole objects that are being looped over in the foreach loop. What I want to do has nothing to do with the ajax call – Robert Ross Jan 28 '17 at 20:28
  • Can you please show how to display the data from the attributes in the modal? – Robert Ross Jan 28 '17 at 21:20
  • for each , the name here is what is important, inside the click event var name = parent.find('input[name="NAME_OF_MODEL"]').val(); get the value of NAME_OF_MODEL, var titleLocation = $('#myModal').find('.modal-title'); get the modal title area, you can get the body of the modal replacing .modal-title with .modal-body... titleLocation.text(name); <--- this display the data – Weslley Ramos Jan 28 '17 at 21:27