C# DropDownListFor OnChange JQuery未通过代码运行

C# DropDownListFor OnChange JQuery未通过代码运行,c#,jquery,asp.net-mvc-4,C#,Jquery,Asp.net Mvc 4,我有一个带有DropDownList的编辑器模板,用于: @Html.DropDownListFor(model => model.task_state_id, new SelectList((System.Collections.IEnumerable)ViewData["TaskStates"], "task_state_id", "state"), new { @Id = "ddlState" }) 在我看来,我有这样一个脚本: <s

我有一个带有DropDownList的编辑器模板,用于:

    @Html.DropDownListFor(model => model.task_state_id,
    new SelectList((System.Collections.IEnumerable)ViewData["TaskStates"], "task_state_id", "state"),
             new { @Id = "ddlState" })
在我看来,我有这样一个脚本:

<script type="text/javascript">
$(this.document).ready(function () {
    $('#ddlState').change(function () //wire up on change event of the 'country' dropdownlist
    {
        var selection = $('#ddlState').val(); //get the selection made in the dropdownlist
        alert("ho");
        if (selection === 4) {
            alert("hi");
            $('#CompletionDate').val() = @DateTime.Now.Date;
        }
        var completion = $('#CompletionDate').val();
        alert(completion);
    })
});
</script>
如果(selection==4),代码可能有一些问题。如果(选择==4) 我认为这个变量不是一个对象,所以你不需要使用'=='
无论如何,也许您应该使用Chrome web developer插件来跟踪其行为。

浏览器控制台中是否有任何错误?这将是脚本呈现顺序问题。在您的视图中,使用
@section-scrpts{your-scrpt here}
。在结束正文之前,请确保您在
\u Layout.cshtml
中的
@RegisterSection(“scripts”,true)
tag@StephenMuecke,你好。我觉得你帮了我这么多-不妨把这一切都给我写下来P我在控制台中没有看到任何错误,这就是为什么我有点困惑的原因您应该在引号中保留日期值,由于jquery val是函数,我们应该像
$inputObj.val('value')
var selection=$('ddlState').val()那样设置val
将返回一个字符串(例如“4”),因此4==“4”为false,但4==“4”为true。如果要设置值,还需要使用
$('#CompletionDate').val('@DateTime.Now.Date')
@section Scripts{

<script type="text/javascript">
$(this.document).ready(function () {
    $('#ddlState').change(function () //wire up on change event of the 'country' dropdownlist
    {
        var selection = $('#ddlState').val(); //get the selection made in the dropdownlist
        if (selection == '4') {
            $('#CompletionDate').val('@DateTime.Now.Date');
        }
        var completion = $('#CompletionDate').val();
        alert(completion);
    })
});
</script>
}