Always wanted, how to make the MVC model not automatically add database fields

Source: Internet
Author: User
Tags http post

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 " 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:

    • Generates the SELECT element and the associated option element for the model property.

    • has HTML helper alternatives Html.DropDownListFor andHtml.ListBoxFor

Select Tag HelperSpecifies 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> 


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"},};}}    

Indexmethod 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);}


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.