简体   繁体   English

如何在javascript中访问对象属性?

[英]How to access object properties in javascript?

I am passing an object(model) in View where I have javascript code written. 我在View中传递了一个对象(模型),并在其中编写了JavaScript代码。 The object has certain properties that I want to access in javascript in order to create a drop down list from the values of those properties. 该对象具有某些我想在javascript中访问的属性,以便从这些属性的值创建一个下拉列表。 Here is my object: 这是我的对象:

public class TestObject
{
    public BuildData ExteriorColor { get; set; }
    public BuildData InteriorColor { get; set; }
 }

and

public class BuildData
{
    public List<ExteriorInteriorData> Data { get; set; }
    public bool isInstalled { get; set; }
    public BuildData()
    {
        Data = new List<ExteriorInteriorData>();
    }
}

Now in the View I have an object of TestObject through ViewData and I want to populate the values present in List<ExteriorInteriorData> in a select list. 现在在视图中,我通过ViewData有一个TestObject对象,我想在选择列表中填充List<ExteriorInteriorData>中存在的值。 Basically I want to do something like this: 基本上我想做这样的事情:

for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
            $("#Exterior_Color").append($("<option " + (i == 0 ? "selected" : "") + "></option>").val(data.ExteriorColor.Data[i].ColorName + ", " + data.ExteriorColor.Data[i].RgbValue).html(data.ExteriorColor.Data[i].ColorName));
    } 

So, How do I access the object TestObject present in Viewdata inside of Javascript? 那么,如何访问Java内Viewdata存在的对象TestObject

if you are writing JavaScript in same view then you just need to convert your model object in js object using this code. 如果您在同一视图中编写JavaScript,则只需使用此代码将模型对象转换为js对象。

var jsModel = @Html.Raw(Json.Encode(Model))

if you want in external file then create an html element and set this model in data- field and get this model in js like this 如果要在外部文件中创建一个html元素,然后在data-field中设置此模型,然后在js中获取此模型,如下所示

View 视图

<div data-JsObject="@Html.Raw(Json.Encode(Model))" id="JSOBJ"> </div>

JS External file JS外部文件

var list = JSON.parse($("#JSOBJ").data("JsObject"))

I hope it'll work for you. 希望对您有用。

except of javascript you can use defualt razor helper for create dropdownlist : 除javascript外,您可以使用defualt razor helper创建dropdownlist:

@Html.DropDownListFor(model => model.ExteriorColor.Data, new SelectList(Model.ExteriorColor.Data, "Value", "Text"))

repale Value and Text By properties in ExteriorInteriorData 外观值和内部属性中的Repale值和Text By属性

Try this. 尝试这个。 Use for loop within the tag. 在标记内使用for循环。

@model [yourproject].Models.TestObject
<select id="Exterior_Color" name="Exterior_Color">
    @foreach (var item in this.Model.ExteriorColor)
    {
        <option value="@item.RgbValue">@item.ColorName</option>
    }
</select>

You can simply get selected item from javasrcipt 您可以简单地从javasrcipt获取选定的项目

$("#Exterior_Color").val();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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