2013-12-01 3 views
0

Я создал пользовательский интерфейс, как показано ниже: Когда пользователь выбирает страну из раскрывающегося списка, тогда представление возвращается динамически. В этом представлении есть имя штата, список важных городов и текстовое поле для ввода комментариев.ASP.NET MVC - Возвращает сложный объект из представления в контроллер

Теперь, когда пользователь выбирает несколько значений (более одного) из выпадающих списков, вводит некоторые комментарии и затем нажимает кнопку «Отправить», эти данные должны быть переданы контроллеру для дальнейшей обработки. Теперь я хочу передать список объектов контроллеру. Один элемент списка должен быть ниже пунктов:

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

Html оказывает негативное воздействие, так что я думаю, что ur не получил ожидаемый формат, поэтому я его изменил, и отлично отобразится то, что вы хотите. Я также добавляю скриншот для вашего ответа. так что вы должны изменить свой яваскрипта код ниже:

<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

Смежные вопросы