D
D
dimayudin3572016-08-31 13:54:13
ASP.NET
dimayudin357, 2016-08-31 13:54:13

How to create and display elements in the same view (the view is strongly typed)?

There were two strongly typed views: Summary (for displaying cities) and Create (for creating new cities)
in Summary: @model IEnumerable<City>, in Create @model City
Both display and create worked fine.
I merged the views, and Create stopped working (In the controller, the Post method comes Null ).
I suspect the problem is that the @model directive is now IEnumerable.
Tell me what could be the problem.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Nemiro, 2016-08-31
@AlekseyNemiro

We need to create a new model that will include IEnumerable<City> and City .
More or less like this:

public class NewModel
{

  public IEnumerable<City> CitiesList { get; set; }

  public City City { get; set; }

}

Use:
@foreach(var city in Model.CitiesList)
{
  // список
}

@Model.City.КакоетоСвойство

For convenience, you can make partial views and pass CitiesList and City into them . The first view should expect an IEnumerable<City> , the second should expect a City . Those. will be approximately what you already have, just ordinary views need to be made partial (remove everything related to templating). Display these views in a shared view, passing values ​​from the shared view model ( NewModel ) to their model:
@model NewMode

@Html.Partial("CitiesList", Model.CitiesList)

@Html.Partial("CityEditor", Model.City)

Partial view of CitiesList :
@model IEnumerable<City>

// ...

Partial view of CityEditor :
@model City

// ...

F
Fat Lorrie, 2016-08-31
@Free_ze

@model is required for rendering , it should not affect model binding .
That is, if the method matches your routing Create(City city), then the binding will try to find among the ValueProviders the values ​​that match the names of the model properties (in this case - City).
What binding errors are you getting?

D
dimayudin357, 2016-08-31
@dimayudin357

b3616815d9124e24af05930862bcd07e.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question