How to load a partialview and store it in a variable to be used in javascript?
Asked Answered
R

1

6

I have a prtialview using a model to create a dropdown list. In my main view I create the partialview html string to use it in javascript functions later.

View:

@model SomeViewModel
@{ 
var devicesDropDown = @Html.Partial("_DropDown", (SelectList)(Model.DeviceTypes));
var devicesHtmlDropDown = MvcHtmlString.Create(devicesDropDown.ToString());
}

But when I want to use it in javascript this way , it is like a unconnected string that causes javascript function an error.

Js function at the buttom of page:

<script type="text/javascript">
   function format(d) {
       var ddl = '@( devicesHtmlDropDown)';
       return ddl;
   }
</script>

This is how string is look like in runtime:

 var ddl = '<select class="form-control input" id="SelectedValue"  name="SelectedValue" style="width: 100%">
<option selected="selected" value="456413">1</option>
<option value="564655465">2</option>
</select>
';

How should I format this string to can render like a static html object. And how can I retrive selected value of this dropdown to post to an action? Should I use TagBuilder?

Raspberry answered 10/2, 2016 at 19:12 Comment(0)
S
6

My suggestion would be to use a script block to hold your template. You can easily retrieve the HTML from there by ID. The script block will never be directly rendered, so it is safely hidden until you extract and apply the HTML.

<script id="ddlTemplate" type="text/html">
    @Html.Partial("_DropDown", (SelectList)(Model.DeviceTypes))
</script>

Then later, you can access this HTML like so (using jQuery)

var template = $('#ddlTemplate').html();
Skewer answered 11/2, 2016 at 5:20 Comment(4)
Using RenderPartial like this : return '@{Html.RenderPartial("_DropDown", (SelectList)(Model.DeviceTypes));}' returns empty string.Raspberry
Your original solution works better. I put @{Html.RenderPartial("_DropDown", (SelectList)(Model.DeviceTypes));} in my html codes and then use it in javascripts like this : ` var template = $('#ddlDevices').html();` that ddlDevices is the id of a containing div in partialview to get its inner html. Thank you.Raspberry
And your original solution is working with @Html.Partial not RendePartialRaspberry
Oops, you are correct, I inadvertently switched contexts (habit)... Use @{Html.RenderPartial( ... ); } or @Html.Partial( ... ) to write to the output. I've remove my other answer, keeping only the solution and corrected this issue.Skewer

© 2022 - 2024 — McMap. All rights reserved.