Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 807
Forough Avatar asked Feb 10 '16 19:02

Forough


People also ask

Can I use JavaScript in partial view?

JavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a @Html.

How to Load partial view in view?

To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.

How to create partial views?

To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view. It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.


1 Answers

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();
like image 170
Kevin Burdett Avatar answered Oct 23 '22 01:10

Kevin Burdett