Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c# - Bind model during post of form inside EditorTemplate (on array)/multiple bind prefixes?

I have a complex Model containing an array. For rendering items for this array I'm using EditorFor like this:

for (int i = 0; i < Model.Contacts.Phones.Length; i++)
{       
    @Html.EditorFor(x => x.Contacts.Phones[i])
}

Inside editor there is a post-form. Problem is, that binding is successful only when I exactly specify binding prefix:

[HttpPost]
public ActionResult SavePhone(
    [Bind(Prefix = "Contacts.Phones[0]")]Contact5UsedPhone model)
{ ... }

So it works only for first of the elements. What is the correct form of prefix?

For the more there is also on the same page editor for different property - but same type of model and same action is therefore executed. Is it possible to set more than one binding prefix? E.g.

[HttpPost]
public ActionResult SavePhone(
    [Bind(Prefix = "Contacts.Phones[0], Contacts.AnotherPrefix")]
    Contact5UsedPhone model)
{ ... }

Thank you!

edit - model:

public class ContactsViewModel
{
    public Contact5UsedPhone AddiblePhone {get;set;}
    public Contact5UsedPhone[] Phones {get;set;}
    ...
}

edit - answer: I found a solution for this. As there is one array (Phones) and one single entity (AddiblePhone), I used two parameters and simple if:

[HttpPost]
public ActionResult SavePhone(
    [Bind(Prefix = "Contacts.Phones")]Contact5UsedPhone[] models, 
    [Bind(Prefix = "Contacts.AddiblePhone")]Contact5UsedPhone model)
{
    model = model ?? models[0];
    ...
}

The question still remains - what if there were AddiblePhones as array? Is it possible to use two prefixes for one parameter, or does it have to be divided to two parameters as I did in this case?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...