ASP.NET MVC - 将复杂对象从视图返回到控制器

时间:2013-12-01 22:17:06

标签: c# jquery asp.net-mvc asp.net-mvc-3

我创建了一个如下界面的UI:当用户从下拉列表中选择一个国家/地区时,视图已动态返回。此视图具有州名称,重要城市列表和输入注释的文本框。

现在,当用户从下拉列表中选择一些值(多个)时,输入一些注释,然后按“提交”按钮,这些数据应该传回控制器进行进一步处理。现在我想要的是我想将一个对象列表传递给控制器​​。一个列表项应具有以下项目:

Country, State, SelectedCity, Comment

enter image description here

以下是我的模特:

public class CountryModel
{
    public string Country { get; set; }
    public string State { get; set; }
    public List<string> Cities { get; set; }

    public static IEnumerable<CountryModel> GetLocationDetails()
    {
        return new List<CountryModel>()
        {
            new CountryModel { Country = "India", State = "WB", Cities = new List<string>(){ "Kolkata", "Kharagpur", "Darjeeling" } },
            new CountryModel { Country = "India", State = "AP", Cities = new List<string>(){ "Hyderabad", "Vizag", "Vijaywada" } },
            new CountryModel { Country = "India", State = "UP", Cities = new List<string>(){ "Kanpur", "Allahabad", "Agra" } },
            new CountryModel { Country = "India", State = "MH", Cities = new List<string>(){ "Mumbai", "Pune", "Nagpur", "Nasik", "Aurangabad" } },
            new CountryModel { Country = "India", State = "RJ", Cities = new List<string>(){ "Jaipur", "Kota", "Jaisalmer" } },
            new CountryModel { Country = "USA", State = "CA", Cities = new List<string>(){ "San Francisco", "Los Angeles", "Oakland" } },
            new CountryModel { Country = "USA", State = "WA", Cities = new List<string>(){ "Seattle", "Bellevue", "Yakima" } },
            new CountryModel { Country = "USA", State = "NY", Cities = new List<string>(){ "New York City", "Buffalo", "Albany" } },
        };
    }

    public List<SelectListItem> Countries { get; set; }
    public List<string> Comments { get; set; }
}

控制器:

public class CountryController : Controller
    {
        public ActionResult Select()
        {
            CountryModel viewmodel = new CountryModel();

            viewmodel.Countries = new List<SelectListItem>()
            {
                new SelectListItem { Text = "India", Value = "India", Selected = true },
                new SelectListItem { Text = "USA", Value = "USA" }
            };

           return View(viewmodel);
        }

        public JsonResult GetCountryDetails(string id)
        {
            var query = from c in CountryModel.GetLocationDetails()
                        where c.Country == id
                        select c;

            return Json(new { query }, JsonRequestBehavior.AllowGet);
        }
}

查看

model MvcApplication2.Models.CountryModel
@{
    ViewBag.Title = "Select";
}
<h2>Select</h2>

@using (Html.BeginForm())
{
    @Html.Label("Select a Country:  ")
    @Html.DropDownListFor(m => m.Countries, Model.Countries)

    <div id="dynamictable"></div>

<script type="text/javascript">
    $(document).ready(function () {
        $('#Countries').change(function () {
            var url = '/Country/GetCountryDetails/' + $('#Countries').val();

            $.getJSON(url, function (result) {
                if (result.query.length > 0) {
                    if ($('#tblResult').length) {
                        $('#tblResult').remove();
                    }

                    $('#dynamictable').append('<table border="1" id="tblResult"></table>');
                    var table = $('#dynamictable').children();
                    table.append('<th>State</th> <th>City</th> <th>Comments</th>');

                    var random = 1;

                    $.each(result.query, function (i, location) {
                        var ddlId = "citiesInState";
                        var finalDdlId = ddlId.concat(random.toString());

                        var markup = '<tr class="locationInfo"><td class="stateCode">' + location.State + '</td><td class="citiesList"><select id="' + finalDdlId + ' name="Cities""></select></td><td class="userCommentsOnLocation">@Html.TextBoxFor(m=>m.Comments)</td></tr>';
                        table.append(markup);

                        var option = '';
                        for (var i = 0; i < location.Cities.length; i++) {
                            $('#' + finalDdlId).append('<option value="' + location.Cities[i] + '">' + location.Cities[i] + '</option>');
                        }

                        random++;
                    });
                }
            });
        });
    });

</script>
<br />
<input type="submit" value="Submit" id="SubmitId" />
}
下面的

是我的POST动作方法:

[HttpPost]
        public ActionResult Select(CountryModel cm)
        {
            if (cm == null)
            {
                throw new ArgumentNullException("cm");
            }

            return View("Display", cm);
        }

但是现在我没有得到预期格式的项目。如何更改我的模型和代码以适应这种情况?任何帮助表示赞赏

1 个答案:

答案 0 :(得分:1)

Html呈现错误,所以我认为你没有获得预期的格式,所以我已经改变了它,并且完美地显示了你想要的内容。我还附上你的答案截图。 所以你必须用以下内容更改你的javascript代码:

<script type="text/javascript">
    $(document).ready(function () {
        $('#Countries').change(function () {

            var url = '/Country/GetCountryDetails/' + $('#Countries').val();

            $.getJSON(url, function (result) {
                debugger;
                if (result.query.length > 0) {
                    if ($('#tblResult').length) {
                        $('#tblResult').remove();
                    }

                    $('#dynamictable').append('<table border="1" id="tblResult"></table>');
                    var table = $('#dynamictable').children();
                    table.append('<th>State</th> <th>City</th> <th>Comments</th>');

                    var random = 1;

                    $.each(result.query, function (i, location) {
                        debugger;
                        var ddlId = "citiesInState";
                        var finalDdlId = ddlId.concat(random.toString());

                        var markup = '<tr class="locationInfo"><td class="stateCode">' + location.State + '</td><td class="citiesList">';
                        markup = markup + '<select id="' + finalDdlId + '" name="Cities"></select>';
                        markup = markup + '</td><td class="userCommentsOnLocation">@Html.TextBoxFor(m => m.Comments)</td></tr>';
                        table.append(markup);

                        var option = '';
                        for (var i = 0; i < location.Cities.length; i++) {
                            $('#' + finalDdlId).append('<option value="' + location.Cities[i] + '">' + location.Cities[i] + '</option>');
                        }

                        random++;
                    });
                }
            });
        });
    });

</script>

通过应用我的代码获得的屏幕截图:

enter image description here