Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout dropdown list pass selection to model in MVC5

I am having a issue with a knockoutjs drop-down list, I have a MVC 5 application with this on my razor view, which is being bound from knockout.

<select name="alddlname" id="alddl" 
    data-bind="
        options: authorityLevel, 
        optionsText: 'AuthorityLevel', 
        optionsValue: 'aid', 
        value: aid
    ">
</select> 

I would link to the use the selected item and pass it to a model attribute

public List<authorityLevel> authLevellistItems { get; set; }
public string SelectedAuthType { get; set; }

I would like to bind the model to the dropdown list so that selectedAuthType is then set to the value

the dropdown is poppulated from knockout with this

var authorityLevelList = Html.Raw(JsonConvert.SerializeObject(ViewBag.authorityLevelDDL));

$(document).ready(function ()
{
    var vm = new AppViewModel();            
    vm.authorityLevel = ko.mapping.fromJS(@authorityLevelList);
    ko.applyBindings(vm);
});

thank you in advance

like image 884
AlanMorton2.0 Avatar asked Jun 20 '14 10:06

AlanMorton2.0


1 Answers

OK so i have figured it out

if i use the @html.DropDownListFor helper and still bind my data attributes from knockout I have a DropDown list that is populated by knockout json array object, but then also bind this to the MVC 5 model this then can be passed back to a controller and inserted to a database.

// the data_bind part is the knockout.js part the rest is the razor c# view helper

@Html.DropDownListFor(m => m.SelectedAuthType, 
        (SelectList)Model.authlevellistItems, 
new { id = "alddl", data_bind = " options: authorityLevel, optionsText: 'AuthorityLevel', optionsValue: 'aid'" }) 

hopefully this will help others and my question wasn't just a waste of time. Thanks A

like image 64
AlanMorton2.0 Avatar answered Oct 14 '22 22:10

AlanMorton2.0