0

I'm using ASP.NET MVC. I've an action which I call to get partial view. I'm using @Html.Action() in order to get the partial view. It works fine but for only id=533. Let's say when user clicks a grid button we can call a Javascript function. From that function how can I pass id and tab values to Html.Action() and retrieve partial view html/js. FYI - Javascript of Partial View must work too.

<div ng-controller="submissionDashboardController">
    @Html.Action("SubmissionHeader", "Submission", new { id = 533, tab = 0 })
</div>

@using (Html.RequiredScripts())
{
    @Html.RequirePageScript("Shared", "ShortcutLinks")
    @Html.RequirePageScript("Submission", "ListSubmissionDashboard")
    @Html.RequirePageScript("Shared", "GridPersonalization")
    @Html.RequirePageScript("Shared", "SubmissionCreation")
}

This is SubmissionHeader Action in Submission Controller.

[ChildActionOnly]
        public ActionResult SubmissionHeader(int? id, SubmissionTabEnum tab = SubmissionTabEnum.None)
        {
            // More logic and code here...

            TempData["SubmissionHeaderID"] = id;
            return PartialView("_SubmissionHeader", model);
        }

Additional Comment/Code : Here is JavaScript Ajax Call to replace div with latest html response. Issue with this approach java script associated with partial view does not work, any event gets triggered from the html response doesn't work.

Div that is getting replaced with html ajax call response.

<div id="comment"></div>

Here is the javascript function which is calling ajax passing dynamic parameters-

<script>

function DisplayCommentDialog(SubmissionID) {
        
        // Ajax Call for Dynamic Parameters and html partial view response
        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: '/Submission/SubmissionHeader',
            async: false,
            data: { id: SubmissionID, tab: 0 },
            success: function (result) {
                commentDiv = result;
                $("#comment").html(commentDiv);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
</script>
Partha
  • 413
  • 2
  • 5
  • 16
  • This question is too broad. What do you mean by "so it works for all ids". How do you intend to pass these ids? – Adlorem Apr 14 '21 at 08:44
  • In the example id = 533. It should work for other ids too such as 516, 578 etc. All these values suppose to pass dynamically not hard coded in code. – Partha Apr 14 '21 at 11:30
  • You can pass parameters in model or viewbag from controller to view. – Adlorem Apr 14 '21 at 12:48
  • I've the ids in model but how can I pass the id dynamically in @Html.Action() when user clicks a button? – Partha Apr 14 '21 at 12:58
  • This must be done for example in javascript. – Adlorem Apr 14 '21 at 13:43
  • I tried that approach, using Java Script I made an ajax call with dynamic id and tab, I get the response back as html. This html has clickable button. When I click that button event is not working. Why javascript in partial view is not working? – Partha Apr 14 '21 at 16:47
  • Hi Adlorem - Thought to check if you got a chance to check this? Any idea on my above comment? – Partha Apr 15 '21 at 12:14
  • Post more of your code. I am interested in your ajax call. What is it doing? – Adlorem Apr 15 '21 at 12:21
  • @Partha: I guess this is what you are looking for: **1)** [Razor view with anonymous type model class](https://stackoverflow.com/a/6613040/6630084) **2)** [Passing anonymous object to view](https://stackoverflow.com/a/9545409/6630084) – Jackdaw Apr 15 '21 at 12:26
  • @Jackdaw - Thank you. Checking those posts. – Partha Apr 15 '21 at 13:44
  • @Adlorem - Added more code/comment related to ajax call. – Partha Apr 15 '21 at 13:51
  • Solved the issue. Answer posted. Thank you all for your help. – Partha May 09 '21 at 18:49

2 Answers2

0

I assume you are trying to replace id in your controller and then pass it to partial view. If so, you can do something like this. Replace

@Html.Action("SubmissionHeader", "Submission", new { id = 533, tab = 0 })

with for example:

<button class="btn btn-secondary" type="button" onclick="DisplayCommentDialog()">Press here</button>

In your partial view create hidden field [Id] with value passed from controller

@Html.Hidden("Id", @id)

Then finaly in you script

<script>

var id = 533; // replace with initial values from model if nesesery
var tab = 0;

function DisplayCommentDialog() {
        
        // Ajax Call for Dynamic Parameters and html partial view response
        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: '/Submission/SubmissionHeader',
            async: false,
            data: { id: id, tab: tab },
            success: function (result) {
                commentDiv = result;
                $("#comment").html(commentDiv);
                id = $($.parseHTML(result)).filter('#Id').val(); // set new id value from result
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
</script>

EDIT

If you are loading button dynamically to DOM you must attach event to document not to specific element.

$(document).on('click','#your_button_id', function(){
   // desired function here
})
Adlorem
  • 1,457
  • 1
  • 11
  • 10
  • Thanks. As I mentioned before Following code $("#comment").html(commentDiv); does replace the div with partial view html but javascipt doesn't work. For Example let's say - comment div has a button and when user clicks that button it does not trigger. Due to some reason Javascript associated with partial view is not accessible. How can I fix that issue? – Partha Apr 16 '21 at 02:05
  • Its because you are loading elements to dom dynamically and event is detached. See my update. – Adlorem Apr 16 '21 at 07:37
  • Totally agree, if we attach event to document like the way you suggested it's able to trigger button from Partial view. I just now tested. Thanks for suggesting this approach. But Partial view has a javascript for example partial.js - this file is doing several other things like onload data population/binding etc. As this .js file is not loaded correctly -- partial view html that we get as the part of ajax response doesn't work correctly. Interestingly @html.Action() somehow able to load that .js file. Not sure how can I achieve using ajax call. Any idea? – Partha Apr 16 '21 at 15:53
  • What does the console says? You are loading javascript in partial view to div so I bet you have error in console. You must load jquery BEFORE this div to make it work. Try to add it to head. The other possibility is to include this js in main view. – Adlorem Apr 16 '21 at 17:14
  • There is no error in console. But I noticed JS file that I'm trying to load gets loaded with @Html.Action("SubmissionHeader", "Submission", new { id = 533, tab = 0 }) but it does not gets loaded if I embed that JS in head or include the file using Html.RequirePageScript(). JS file has AngularJS controller mainApp.controller('submissionHeaderActionsController', ['$scope', '$http', function ($scope, $http, viewDataService) {$scope.showCommentModal = function (e) {alert('showCommentModal');};}]); Not sure if this something to do with AngularJS controller, any idea what it could be wrong? – Partha Apr 18 '21 at 18:00
  • I mean placing jquery in head section. You are using jquery in your project. – Adlorem Apr 19 '21 at 08:54
  • Yes, in BundleConfig.cs they are added and registerd in Layout.cshtml. Also I'm calling $.ajax() call using jQuery on the same page and they are working. Jquery may not be the issue. bundles.Add(new Bundle("~/bundles/flexpaper_readonly").Include("~/Scripts/flexpaper/jquery.min.js","~/Scripts/flexpaper/jquery.extensions.min.js")); – Partha Apr 19 '21 at 11:48
  • This is another question not relevant to my answer to your question "How to make Html.Action parameters dynamic?". If you are satisfied with my current answer mark it as solved and post new question on stackoverflow. – Adlorem Apr 20 '21 at 16:50
  • I finally solved the issue. Thank you all for your help. It helped me to think it through to solve the issue. – Partha May 09 '21 at 18:50
0

Finally I could able to solve this issue by modifying my approach.

Here is what I followed -

  1. I kept comment div exactly like before.

  2. I updated this Div making an ajax call like I was doing at page load and passed parameters dynamically -

    function DisplayCommentDialog(id, tab) {
            
            // Ajax Call for Dynamic Parameters and html partial view response
            $.ajax({
                type: 'POST',
                dataType: 'html',
                url: '/Submission/SubmissionHeader',
                async: false,
                data: { id: id, tab: tab },
                success: function (result) {
                    commentDiv = result;
                    $("#comment").html(commentDiv);
                    id = $($.parseHTML(result)).filter('#Id').val(); // set new id value from result
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                }
            });
        }
    
  3. This will solve the issue with dynamic variable and updated content will be displayed in DIV as I replaced the DIV id and tab values. But please note this will not solve any issue with onclick or onload or any on event. They will be dead after div is updated even if you make js file available. In order to fix this issue I had to rebind all dynamic data , in my case a drop down values by making an ajax call and rebind the drop down - something like this.

    >     <script>
    >         function DisplayCommentDialog(EntityOrganizationID) {
    >             var categories = $("#commentrecipients").kendoDropDownList({
    >                 optionLabel: "Select Recipients...",
    >                 dataTextField: "Name",
    >                 dataValueField: "UserID",
    >                 height: 310,
    >                 Width: "900px",
    >                 dataSource: {
    >                     transport: {
    >                         read: function (options) {
    >                             $.ajax({
    >                                 url: "/Submission/SecurityGroupsUsersAccessRight",
    >                                 dataType: "JSON", // "jsonp" is required for cross-domain requests; use "json" for same-domain
    > requests
    >                                 data: {
    >                                     id: EntityOrganizationID
    >                                 },
    >                                 success: function (result) {
    >                                     // notify the data source that the request succeeded
    >                                     options.success(result);
    >                                 },
    >                                 error: function (result) {
    >                                     // notify the data source that the request failed
    >                                     options.error(result);
    >                                 }
    >                             });
    >                         }
    >                     }
    >                 }
    >             }).data("kendoDropDownList");
    >         }
    >     </script>
    
Partha
  • 413
  • 2
  • 5
  • 16