Search code examples
c#asp.netasp.net-corerazorview

how to bind a viewmodel containing a list and parameters to a controller action from cshtml?


I have a viewModel containing a list and another class like so :

public class MyViewModel
{
    public List<Guids> Ids{ get; set; }

    public History HistoryRecord{ get; set; }
}

public class History
{
    public string UserName{ get; set; }
    public string Email{ get; set; }

}

and a controller action that I need to send the above data to:

public async Task<IActionResult> myAction([Bind("Ids","UserName","Email")] MyViewModel viewModel)
{
... 
    
}

i'm getting the values for userName and Email via inputs

                        <input type="text" class="form-control child " name="name" id="nameTextbox" placeholder="name" required />
                        <input type="text" class="form-control child " name="email" id="emailTextbox" placeholder="email" required />

how can I send this from a razor page?

i've tried using url.Action but this doesnt seem to work and not sure how to put multiple values in

<button type="submit" class="btn btn-primary" id="confirm" onclick="location.href='@Url.Action("myAction","myController", values: new {Ids= @Model.Ids.ToList(), Name = ? , Emil = ? })'">confrim</button>

Solution

  • You can try to add hidden inputs to the form,It looks like you want to use List<Guid> Ids,here is a demo:

    Model:

    public class MyViewModel
    {
        public List<Guid> Ids{ get; set; }
    
        public History HistoryRecord{ get; set; }
    }
    

    add following data to the form:

    @for(var i=0;i<Model.Ids.Count;i++)
    {
        <input asp-for="@Model.Ids[i]" hidden />
    }