ViewComponent不允许操纵DOM

时间:2020-01-02 14:00:52

标签: javascript c# asp.net-core asp.net-core-viewcomponent

在我的.net MVVM应用程序中,我有几个视图组件,这些组件用于呈现从数据库填充的下拉列表。我发现渲染完后无法通过jquery处理(重新选择)下拉列表中的项目。谁能解释这是为什么?

查看组件

@using ViewComponents
@model XXX.Source

@Html.DropDownList(Model.FieldName, new List<SelectListItem>(Model.OptionList),
"Choose",
new {
   @multiple = "multiple",
   @class = "input-sm"
   }

调用视图组件:

<vc:source is-multiple="true" field-name="Source"></vc:source>

查看组件:


using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;


using static XXX.Source;


namespace XXX.ViewComponents
{

    public class SourceViewComponent : ViewComponent
    {
        private readonly IService _Service;

        public SourceViewComponent(IService Service)
        {
            _Service = Service;
        }
        public async Task<IViewComponentResult> InvokeAsync(string fieldName, bool isMultiple = false )
        {

            Source viewModel  = new Source();

            var items = await _Service.GetSourceAsync();
            viewModel.IsMultiple = isMultiple;
            viewModel.FieldName = fieldName;

            viewModel.OptionList =
                from c in items
                select new SelectListItem
                {
                    Value = c.SourceId.ToString(),
                    Text = c.SourceName
                };

            return View(viewModel);

        }

    }
}

我试图在javascript中无法正常工作-毫无效果-是在发布后重新选择多选选项。这是我在用javascript做的事情:

 function populateSelect(fldname, value) {
            alert("Inside populateSelect field " + fldname + " value is [" + value + "]");
            $.each(value.split(","), function (i, e) {   
                alert("setting " + fldname + " to " + e + " selected");
                $("#" + fldname + " option[value='" + e + "']").prop("selected", "selected");
            });
            $(fldname).prop("multiple", "multiple");
        }

   populateSelect("Source", sessionStorage.getItem("Source"));

如果我尝试针对手动创建的下拉列表进行此操作,则效果很好。

页面上的渲染组件如下:

<select class="input-sm" id="Source" multiple="multiple" name="Source" size="4">
<option value="">Choose</option>
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
<option value="3">Choice 3</option>
<option value="4">Choice 4</option>
<option value="5">Choice 5</option>
<option value="6">Choice 6</option>
<option value="7">Choice 7</option>
</select>

请注意,当我运行此populateSelect时,我会在警报调试框中获取适当的数据,因此这些值在那里,并且在将选项设置为selected时没有错误...但是在手动创建的下拉菜单中,它实际上重新选择了选项,而在viewcomponent下拉菜单上则无济于事。

0 个答案:

没有答案