Home > front end >  How to properly handle forms with different data to receive and different to POST in ASP NET Core
How to properly handle forms with different data to receive and different to POST in ASP NET Core

Time:01-14

I have two classes:

public class SomeInfo
{
    public Dictionary<string, string> SomeDictionary1 { get; init; }
    public Dictionary<string, string> SomeDictionary2 { get; init; }
    public string DisplayName { get; init; }
    public string LogoUri { get; init; }
    public bool DeselectionAllowed { get; init; }
}

and

public class ViewModel
{
    public bool Denied { get; set; }
    public string[] ConsentedSomeDictionary1Keys { get; set; } = Array.Empty<string>();
    public string[] ConsentedSomeDictionary2Keys { get; set; } = Array.Empty<string>();
    public bool Remember { get; set; }
}

The class SomeInfo is class that I want to display to user and the class ViewModel is class that I want to receive in my backend. So what shall I do to achieve support for this scenario if I cant use two view models in one view?

CodePudding user response:

When you submitting the data you can try to change the names of the inputs,so that they will be binded to the properties of ViewModel by default.here is a demo to bind the keys of SomeDictionary1 and SomeDictionary2 to ConsentedSomeDictionary1Keys and ConsentedSomeDictionary2Keys:

action:

[HttpGet]
        public IActionResult TestModel()
        {

            return View(new SomeInfo {  SomeDictionary1=new Dictionary<string, string> { {"UK", "London"},{"USA", "Washington"},{"India", "Mumbai"}},
                                        SomeDictionary2=new Dictionary<string, string> { { "1","one"},{ "2","two"},{ "3","three"} }
            });
        }
        [HttpPost]
        public IActionResult TestModel(ViewModel viewModel)
        {
            return Ok();
        }

view:

@model SomeInfo
<form method="post">
    @for (var i = 0; i < Model.SomeDictionary1.Count; i  )
    {
        <input name="ConsentedSomeDictionary1Keys[@i]" value="@Model.SomeDictionary1.ElementAt(i).Key" />
       
    }
    @for (var i = 0; i < Model.SomeDictionary2.Count; i  )
    {
        <input name="ConsentedSomeDictionary2Keys[@i]" value="@Model.SomeDictionary2.ElementAt(i).Key" />
      
    }
    <input type="submit" value="submit"/>
</form>

result: enter image description here

  • Related