【问题标题】:MVC Core: ViewComponent onload event equivalentMVC Core:ViewComponent onload 事件等效
【发布时间】:2017-07-17 12:58:18
【问题描述】:

我在 ASP.NET MVC Core 项目中有一个下拉列表。

<div class="form-group">
   <div class="col-md-10">
       @Html.DropDownListFor(t => t.AnimalTypeID, Model.AnimalTypeList, 
       new { onchange = "performStuff();" })
   </div>
</div>

onchange 事件就像一个魅力,根据下拉选择隐藏某些包含页面字段(即“毛皮颜色”或“喙类型”文本框)。

不过,我也想在 ViewComponent 加载/就绪时调用相同的功能。请问有没有办法做到这一点?

即我基本上希望有这样的等价物,如果可能的话?

@Html.DropDownListFor(t => t.AnimalTypeID, Model.AnimalTypeList, 
       new { onload="alertFunction();" ,onchange = "performStuff();" })

<script type="text/javascript">
    function alertFunction() 
    {
        alert('hello world!');
    }
 </script>

【问题讨论】:

  • 你能在你的解决方案中使用 jQuery 吗?
  • 当然,是的,这是我可以接受的一个选项,谢谢。
  • 在答案中添加了更多详细信息。

标签: asp.net-core asp.net-core-mvc asp.net-core-viewcomponent


【解决方案1】:

ASP.NET MVC Core 版本下拉的 Razor 代码如下。

<select asp-for="AnimalTypeId" asp-items="@Model.AnimalTypeList" onchange="alert('change');">
    <option>Please select</option>
</select>

但是,select 的 JavaScript 事件仅与元素的行为有关。如果需要在页面加载时显示/隐藏其他一些字段,我认为这是页面主脚本的责任。您可以在视图模型中设置显示/隐藏参数以从后端代码控制它,或者使用 jQuery 的

<script type="text/javascript">
    $(function () {  /* Your function */ });
</script>

控制在页面加载时应该隐藏哪些元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多