【问题标题】:changing textbox value on change of a dropdown更改下拉列表时更改文本框值
【发布时间】:2015-12-27 05:24:56
【问题描述】:

我只是想在下拉列表更改时更改文本框的值,你能告诉我有什么问题吗?我真的是 Jquery 的新手

我的控制器中的代码只是一个示例,在我的代码工作之后我会做更多的事情

查看

 <script type="text/javascript">
        $(document).ready(function () {
            $("#ddltype").change(function () {
                var id = $(this).val();
                $.getJSON("@Url.Action("getWeightedAverage", "Employee")", { id: id }, function (Ave) {
                    $("#Average").val(Ave);
                });
            });
        });
    </script>

<fieldset>
    <legend>Grade</legend>

    <div class="editor-label">
        @Html.DropDownListFor(model => model.g_type, new List<SelectListItem>{
        new SelectListItem {Value = "1", Text = "Written Work"},
        new SelectListItem {Value = "2", Text = "Performance Task"},
        new SelectListItem {Value = "3", Text = "Quarterly Assesment"},
        }, new {id = "ddltype" })
        @Html.ValidationMessageFor(model => model.g_type)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.weighted_percent)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.weighted_percent, new { id = "Average" })
        @Html.ValidationMessageFor(model => model.weighted_percent)
    </div>

控制器

    public JsonResult getWeightedAverage(string id)
    {
        string Ave = "40";
        return Json(Ave, JsonRequestBehavior.AllowGet);
    }

【问题讨论】:

  • 为什么 this.Average?,只有 $("#Average").val(Average); 可以工作。
  • 还是不行:(

标签: jquery asp.net json asp.net-mvc


【解决方案1】:

使用从服务器调用返回响应的变量。你不需要 this 那里的关键字。

$(document).ready(function () {
    $("#ddltype").change(function () {
        var id = $(this).val();
        $.getJSON("../Employee/getWeightedAverage", { id: id }, function (res) {
            $("#Average").val(res);
        });
    });
});

我还建议您使用Url.Action 方法来构建url,而不是硬编码。

$.getJSON("@Url.Action("getWeightedAverage","Employee")", { id: id }, function (response) {
   $("#Average").val(response);
});

如果您的代码不在 razor 视图中,而是在外部 js 文件中,则您在 razor 视图中构建基本 url 并在 js 文件中使用它,如this answer.中所述

【讨论】:

  • 它应该可以正常工作。刚刚验证过了。我猜您的页面中还有其他脚本错误。请检查您的浏览器控制台。
  • ReferenceError: $ is not defined addGrade:7:9 哪个部分是我唯一的脚本错误
  • 你是在自定义脚本之前加载 jQuery 吗?
  • 现在工作非常感谢您的帮助!我忘了那个对不起的新手在这里:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
相关资源
最近更新 更多