部分查看数据未回发到控制器

时间:2015-03-15 21:17:12

标签: asp.net-mvc

我正在根据下拉列表值加载部分视图,如以下链接所示。我能够显示部分视图并在文本框中输入值。但是当我回发时,我无法在Controller中获取值。除了这个局部视图值

,我得到所有其他值

Render Partial View Using jQuery in ASP.NET MVC

div id="divFloorPlans"></div>

 $('#ddlFloorPlans').change(function () {
        var numberOfFloorPlans = $(this).val();
        var data = { "id": numberOfFloorPlans };
        $.ajax({
            url: "FloorPlans",
            type: "POST",
            data: data, //if you need to post Model data, use this
            success: function (result) {                  
                $("#divFloorPlans").html("");
                $("#divFloorPlans").html(result);
            }
        });
    });

@model IList<ViewModels.FloorPlan>
@for (int i = 1; i <= Model.Count; ++i)
    {
        <div class="col-md-12" >               
            <div class="col-md-2" >
                @Html.DropDownListFor(m => m[i - 1].Bedrooms, ViewData["Bedrooms"] as List<SelectListItem> })
            </div>
            <div class="col-md-2" >
                @Html.DropDownListFor(m => m[i - 1].Bathrooms, ViewData["Bathrooms"] as List<SelectListItem> })
            </div>
            <div class="col-md-3" >
                @Html.TextBoxFor(m => m[i - 1].MinPrice})
                @Html.TextBoxFor(m => m[i - 1].MinPrice })
            </div>
            <div class="col-md-3">
                @Html.TextBoxFor(m => m[i - 1].MinSqFt, new { @placeholder = "From" })
                @Html.TextBoxFor(m => m[i - 1].MaxSqFt, new { @placeholder = "To"})
            </div>              
        </div>
    }

我的模型看起来像这样。

  public class ItemEditVM
{
  public FloorPlan FloorPlan { get; set; }

    public IList<FloorPlan> ListFloorPlans { get; set; }
}

我的控制器

    //Partial View Returning Controller
    [HttpPost]
    public ActionResult FloorPlans(int id)
    {
        var model = new ItemEditVM();

        model.NumOfFloorplans = id;

        model.ListFloorPlans = new List<FloorPlan>();

        for (int i = 0; i < id; i++)
        {
            model.ListFloorPlans.Add(new FloorPlan { FloorPlanName = "", Bathrooms = "", Bedrooms = "", MaxPrice = "", MinPrice = "", MaxSqFt = "", MinSqFt = "" });
        }

        return View("FloorPlan", model.ListFloorPlans);
    }

    //Create Controller
    [HttpPost]
    public ActionResult Create(ItemEditVM model)
    {
        if (ModelState.IsValid)
        {

        }
    }

1 个答案:

答案 0 :(得分:2)

您使用

生成控件的部分视图模型为IList<FloorPlan>
<input name="[0].MinPrice" ..>
<input name="[1].MinPrice" ..>

会回发到IList<FloorPlan> model,但您的方法参数为ItemEditVM model。您需要将部分视图模型设为@model ItemEditVM

在GET方法中

return View("FloorPlan", model);

并在视图中

@model ItemEditVM
@for (int i = 1; i <= Model.ListFloorPlans.Count; ++i)
{
    ....
    @Html.TextBoxFor(m => m.ListFloorPlans[i - 1].MinPrice})
    ....
}

将生成用于绑定到模型的正确名称属性

<input name="ListFloorPlans[0].MinPrice" ..>
<input name="ListFloorPlans[1].MinPrice" ..>