Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
Binding a Nested Object in ASP.NET MVC - Razor

My ASP.NET MVC viewmodel is designed as below

public class Customer
{
  public int CustomerId{ get; set; }
  public string CustomerName{ get; set; }
  public Address CustomerAddress {get;set;}
}


 public class Address
{
   public int AddressId{ get; set; }
   public string HouseName{ get; set; }
   public string Location{get;set;}
}

How can I bind Address object properly in cshtml page so that it should be available after form Submit.

In cshtml page I want bind it the properties as below

 @model CustomerManagement.Model.ViewModels.Customers.Customer
 @using (Html.BeginForm())
   {
     @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form- 
   control readOnlySchdCode", @readonly = "readonly" } })
    @Html.Hidden("AddressId", Model.Address.AddressId)
    @Html.Hidden("HouseName", Model.Address.HouseName)
   }

In controller form submit will look like as below

    public async Task<ActionResult> AddCustomer(Customer model)
    {
       //How can i access Address properties eg:model.CustomerAddress.AddressId??
    }

Can anyone share a sample code on how to bind the Above viewmodel properly in cshtml using razor template and how properties are properly retrieved in Action method while form submit.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Here is a little example

    public class BigViewModel : IModelOptions
    {
       public bool Confirm { get; set; }
       public SmallViewModel SmallView { get; set; }
    }

    public class SmallViewModel
    {
       public string Stuff{ get; set; }
    }

    public interface IModelOptions
    {
       SmallViewModel SmallView { get; set; }
    }

and our controller would be like

    public class HomeController : Controller
    {
       public ActionResult Index()
       {
          return View();
        }

        [HttpPost]
        public ActionResult Index(BigViewModel model)
        {
           var smallVIewModelInfo = model.SmallView.Stuff;
           var bigViewModelConfirm = model.Confirm;
           return View();
        }
    }

using view like

    @model MvcApplication1.Models.BigViewModel
over 4 years ago · Santiago Trujillo Relatório

0

You could try this way.

Client side:

@using Newtonsoft.Json.Linq
@using WebAppDemo.Models
@model WebAppDemo.Models.Customer

@{
    ViewData["Title"] = "Home Page";
}


@{
    ViewBag.Title = "Home Page";
}
<br />
@using (Html.BeginForm("AddCustomer", "Home", FormMethod.Post, new { id = "Form1" }))
{
    <div class="row">
        <div class="col-lg-2">Cust Id</div>
        <div class="col-lg-10">
            @Html.TextBoxFor(a => a.CustomerId, new { @class = "form-control" })
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-2">Customer Name</div>
        <div class="col-lg-10">
            @Html.TextBoxFor(a => a.CustomerName, new { @class = "form-control" })
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-2">Address</div>
        <div class="col-lg-10">
            @Html.TextBoxFor(a => a.CustomerAddress.HouseName, new { @class = "form-control" }) 
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-lg-12"><input type="submit" value="Submit" class="btn btn-primary"></div>

    </div>
}

Form Output Should Be Like:

enter image description here

Controller:

        [HttpPost] //attribute to get posted values from HTML Form
        public  ActionResult AddCustomer(Customer model)
        {
            return Ok();// For testing I just kept it as `Ok` You can return `View()`;
        }

Note: Please try to pass value on form as per Model property descriptions. Other than you might get null value.

Output:

enter image description here

Hope it will help you. Let me know if you have any further concern.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda