【问题标题】:MVC Razor View update Form on SelectedIndexChangeSelectedIndexChange 上的 MVC Razor 视图更新表单
【发布时间】:2015-04-18 04:34:39
【问题描述】:

我在视图中有一个表单,它汇集了许多信息(地址、电话等)。所有这些元素都包含在视图模型中。有一个部分要求用户选择一个县。在选择时,我希望能够根据所选县显示价格。

我遇到了以下SO question,这与我想要的很接近,但看起来该操作将表单提交给“更改控制器”。我天真地需要能够基本上调用两个控制器 - 一个 onSelectedChange 和另一个 onSubmit。我很确定你不能这样做!

这是我想要的:

@model ViewOrder

@using (Html.BeginForm("Order", "Home"))
{
    @* - textboxes et al - *@

    <p>
        @Html.DropDownListFor(x => x.Counties, 
          new SelectList(Model.Counties, "CountyId", "County"), 
          new { @class = "form-control  input-sm" })
    </p>
    <p>
        @* - £Price result of dropdown list selection and 
        add to View Model to add to sub total - *@
    </p>

    <input type="submit" text = "submit"/>
}

我对 MVC 很陌生 - 可以在 web 表单中轻松做到这一点(但我坚持使用 MVC!)必须有某种形式的 Ajax 操作可以实现这一点。有什么建议吗?

【问题讨论】:

    标签: ajax razor asp.net-mvc-5 html.dropdownlistfor selectedindexchanged


    【解决方案1】:

    首先你的@Html.DropDownListFor()方法有问题。 Model.Counties 是一个复杂对象(具有属性CountyIdCounty),但您不能将&lt;select&gt;(或任何控件)绑定到复杂对象,只能绑定值类型。你的模型需要一个属性(比如)public int SelectedCountry { get; set; },然后是@Html.DropDownListFor(x =&gt; x.SelectedCountry, new SelectList(Model.Counties, "CountyId", "County"), ...)

    要显示价格,您需要处理下拉列表的.change 事件,将选定的值传递给控制器​​方法,并更新 DOM。

    脚本(基于属性为SelectedCountry

    var url = '@Url.Action("GetPrice", "yourControllerName")';
    $('#SelectedCountry').change(function() {
       $.getJSON(url, { ID: $(this).val() }, function(data) {
         // do something with the data returned by the method, for example
         $('#someElement').text(data);
       });
    });
    

    控制器

    public JsonResult GetPrice(int ID)
    {
      // ID contains the value of the selected country
      var data = "some price to return";
      return Json(data, JsonRequestBehavior.AllowGet);
    }
    

    【讨论】:

    • 哇!那是一种享受(并不是说我有任何疑问!)。我显然有很多东西要学,但我现在又要更上一层楼了。
    猜你喜欢
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多