Related entity validation

I have a model like this:

public class Person
{
    public int ID { get; set; }

    [Required(ErrorMessage="Name cant be empty")]
    public string Name { get; set; }

    public Person Friend { get; set; }
}

I want to create a new Person and make a form with fields using a strongly typed HtmlHelper

  •   
  • ID  
  • Name  
  • Friend ID (drop-down list with options such as <option value="Friend.ID">Friend.Name</option>

alt text

When submitting the form, my controller takes a Person ( p) object , which is bound using the default simulated object. In order to be explicit, modelbinder does the following: properties IDand Nameare bound as expected. Friendset to a new instance Personwhose IDequal ID is the person I selected in the drop-down list. The value Friend.Nameis equal nullbecause I did not provide a value for it in the form.

: , RequiredAttribute Name, , . , name Friend. , , , , ModelState , , p.Friend.Name . alt text

? Friend. :

  • ViewModels , - . , , .
  • friend_id Friend . ID Name , Friend. Friend friend_id, "" Person.
  • ModelState , , . ( , , , SecondFriend

, 2 , , . , , friend_id textbox 'Name .

, , , . , . , , ViewModel, , , , .

ViewModels ID, Name friend_id , Person. ID Name Person. Friend . newPerson.Friend = repository.Get(viewModel.Friend_id)

, AutoMapper, "".

+3
2

, . , , : Name on Person Name on Friend.

, . , VarName.PropertyName. , :

  • p.Name
  • p.Friend.Name

ClassName.PropertyName , , .

? - , ( ). , -- Html. Html.TextBoxFor Html.TextBox .

, , , Html (, ), , :

Html.TextBoxFor("p", model => model.Friend.Name);

<input type="text" name="p.Friend.Name" id="p_Friend_Name" />

, . .

+1

, Person, Friend , Name.

,

:

  • p.Name
  • p.ID
  • p.Friend.ID

p.Friend.Name.

, - , ( , , ).

, p.Friend.Name.

+1

Source: https://habr.com/ru/post/1764543/


All Articles