简体   繁体   中英

How to set a knockout property with a MVC model view property in a partial view

i have the next scenario:

Im working with knockout (ver 2.1.0) and ASP MVC.NET, so in one specific point my controller calls a new view. This view renders a partial view with the next call:

<div id="productSeriesNonSocks">
    @{
    Html.RenderPartial("~/Views/SalesOrderManagement/GetAvailableProductSeriesNonSocks.cshtml", Model);
     }
</div>

The controller called the view with a viewModel (Model) with a few properties, so the above call sends the whole model to the partial view.

In the partial view I can access the model properties with a simple sentence like this:

Available season type: @Model.SeasonType

The problem starts here... the partial view has it own knockout model:

<script type="text/javascript">
$(function () {
    //activates KO
    ko.applyBindings(productSeriesNonSocksModel);
    GetDataFromModels();
});

var productSeriesNonSocksModel = {
    AvailableProductSeriesNonSocks: ko.observableArray([]),
    selectedProdSeries: ko.observable(),
    seasonType: ko.observable()
};

function GetDataFromModels() {
    $.get('/SalesOrderManagement/GetAvailableProductSeriesNonSocks', { seasonType: this.seasonType() }, function (data) {
        productSeriesNonSocksModel.AvailableProductSeriesNonSocks(data.AvailableProductSeriesNonSocks);
    });
}

</script>

the GetDataFromModels() function should call a method in the controller with the seasonType as a parameter in order to retrieve the proper array and put it on the AvailableProductSeriesNonSocks array. The problem here is that I don't know how to pass the value from a property model (in this case @Model.SeasonType) to the knockout model to call the function in the controller (productSeriesNonSocksModel.seasonType).

I tried to pass the value with:

seasonType: ko.observable(@Model.SeasonType)

or

seasonType: @Model.SeasonType

but it doesn't work. Any idea to pass a model property value to the knockout property value in order to make the call with the $.get(...)?

To clarify, I can't just ask the value because that value (SeasonType) was choosen by the user in the previous view.

Thank you in advance.

You can use razor in script tags.

<script type="text/javascript">
    var seasonType = @Model.SeasonType;
    // do something with season type
</script>

It might also make sense to avoid the additional request. You could put the data from "/SalesOrderManagement/GetAvailableProductSeriesNonSocks" in the model or the ViewBag and render that as JavaScript Object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM