0

in my javascript I'm trying to build a string that will be html and inside that string i also want to use MVC's Html.Action helper. I want to append this to some <div> element. Works fine if i take out the line @Html.Action. Am i going about this right or is this done some other way?

function Conditionalpartialview(MyParamID) {
    var html =
        '<br />' +
        '<div id="SurveyQuestionConditionalLogic_' + MyParamID + '">' +
            '<span id="SurveyLogicIDsarr_' + MyParamID + '" >' + MyParamID + '</span>' +
         '@Html.Action("ControlerActionMethod", "Home", new { ID = MyParamID })' +
        '</div>'
    $("div").append(html);
}
7
  • Thanks plenty for reformatting it Stephen.. Commented Mar 24, 2017 at 4:11
  • 2
    You cannot. @Html.Action() is razor code and its parsed on the server before its sent to the view. Commented Mar 24, 2017 at 4:12
  • What are you actually trying to do here? If you want to update the DOM, then you need to use ajax to call the controller method and update the DOM in the success callback. Commented Mar 24, 2017 at 4:13
  • So there is no way to call @Html.Action() from javascript. Or there's no way to do this dynamically? Commented Mar 24, 2017 at 4:14
  • 1
    Instead of using Action helper which rendered by server, you can use AJAX call to an action method which returning view/partial view. Commented Mar 24, 2017 at 4:20

1 Answer 1

1

you can do it with ajax call

function Conditionalpartialview(MyParamID) {

var result = '';
$.ajax({
    type: "GET",
    async: false,
    url: "/Home/ControlerActionMethod/",
    data: JSON.stringify({ID:MyParamID}),
    success: function (viewHTML) { 
        result=viewHTML;
    },
    error: function (errorData) { onError(errorData); }
});

    var html =
        '<br />' +
        '<div id="SurveyQuestionConditionalLogic_' + MyParamID + '">' +
                '<span id="SurveyLogicIDsarr_' + MyParamID + '" >' + MyParamID+ '</span>' 
         + result + '</div>'
        $("div").append(html);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly the logic i was looking for.. Thanks a bunch Usman

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.