This problem may be mentally retarded, but troubled me for a long time, the internet has not been able to search, today, a chance to see this in a foreign forum.
First of all, I want to implement the automatic binding to set the Pull option, the web search for a lot of methods, but everyone is using the ViewBag (ViewData) will instantiate the good DropDownList put in the inside and then passed to the front desk, I began to do so, but then inexplicably wrong, That there is no instantiation of the object.
Later I looked at some official documents, where the markup helper in the ASP. NET Core form "https://docs.microsoft.com/zh-cn/aspnet/core/mvc/views/ Working-with-forms?view=aspnetcore-2.1#the-select-tag-helper "chapter, the official document gives the correct binding method, the first summary is as follows:
Select Tag Helper
Specifies asp-for
the model property name for the select element, asp-items
specifying the OPTION element. For example:
HTML Replication
<select asp-for="Country" asp-items="Model.Countries"></select>
Example:
C # replication
Using Microsoft.AspNetCore.Mvc.Rendering;Using System.Collections.Generic;Namespaceformstaghelper.viewmodels{public class CountryViewModel { Span class= "Hljs-keyword" >public string Country {get; set; } public list<selectlistitem> countries {get;} = new list<selectlistitem> {new SelectListItem {Value = "MX", Text = "Mexico"}, new SelectListItem {Value = "CA", Text = new SelectListItem {Value = "US", Text = "USA"},};}}
Index
method to initialize CountryViewModel
, set the selected country/region, and pass it to the Index
view.
C # replication
public IActionResult IndexOption(int id){ var model = new CountryViewModel(); model.Country = "CA"; return View(model);}
The HTTP POST Index
method displays the selected content:
C # replication
[HttpPost][ValidateAntiForgeryToken]public IActionResult Index(CountryViewModel model){ if (ModelState.IsValid) { var msg = model.Country + " selected"; return RedirectToAction("IndexSuccess", new { message = msg}); } // If we got this far, something failed; redisplay form. return View(model);}
Index
View:
CSHTML Replication
@modelCountryviewmodel<Formasp-controller= "Home" asp-action=< Span class= "hljs-string" > "Index" method= "post" > <select asp-for= "country" asp-items= "Model.Countries" > </select> < br/><button type= "submit" >register</button></FORM>
Generate the following HTML (when "CA" is selected):
HTML Replication
<FormMethod="POST"action="/" ><SelectId="Country"Name="Country" ><OptionValue="MX" >mexico</Option><OptionSelected="Selected"Value="CA" >canada</Option><Optionvalue= "US" >usa</ option> </select> <br/>< Button type= "submit" >register</< Span class= "Hljs-name" >button> <input name= "__requestverificationtoken" Type= "hidden" value= "<removed for Brevity> "/> </FORM>
Special notes are included.
It is not recommended ViewBag
or used with the ViewData
Select Markup Helper. The view model is more reliable and generally less prone to problems in providing MVC metadata.
我才发现,其实正确的做法还是用模型还传递数据,我立马照做了,但是在提交的时候又出现了新的问题,
Invalidoperationexception:the entity type ' Selectlistgroup ' requires a primary key to be defined.
Later, after Baidu, on a foreign site, said the need to add "notmapped" in the model attributes of the attribute, the official explanation is: denotes that a property or class should is excluded from Database mapping.
As follows:
[Notmapped] Public list<selectlistitem> Countis {get; set;} = new list<selectlistitem> ();
After the test, sure enough, I understand that the reason for the error is that, without adding this attribute, it also wants to primary Key into the database into the Contis after the selection of data, plus, there is no corresponding operation.
Back to the title, I always want to find a attribute, to describe a field, this field is I need to display in the views, but do not need to save in the database, the most typical example is to register the user when the "Confirm Password" text box, you need it in the views to let the user to input, But you certainly do not save the password and save once "Confirm password", I have not found the corresponding method, in solving the above problem, I determined to add the "notmapped" this attribute to my confirmation password attribute, sure enough, there is no confirmation password field in the rebuilt database. That's great
[Display (Name = "Confirm password")] [Required (errormessage = "You need to fill in {0}")] [Stringlength (errormessage = "{0} length should be between {2} to {1} characters", Minimumlength = 6)] [Compare ("Password", errormessage = "{0} should match {1}")] [DataType (Datatype.password)] [Notmapped] public string ConfirmPassword {get; set;}
Always wanted, how to make the MVC model not automatically add database fields