1

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.

3
  • Have you tried using a Helper Model means a model combination of Customer and Address? Commented Jul 15, 2021 at 6:34
  • @ashhadullah..I am not familiar with that..Can you please explain Commented Jul 15, 2021 at 6:36
  • Hello Is there anything else I can help you with? Commented Jul 16, 2021 at 6:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

So in ViewModel side there is no change required ??How the binding happens on Address object ..So if i am setting hidden field as @Html.Hidden("AddressId", Model.Address.AddressId)..then is it available while Submit ??
No need to change your model. You can keep that as it is, I just made this example keeping all of your code.
Just copy as paste my sample it will work exactly, I am here no worries just let me know if you encountered any more issue.
if i set @Html.Hidden("AddressId", Model.CustomerAddress.AddressId)..then is it available in action method as model.CustomerAddress.AddressId ??
No it will throw an exception. because on load value would be empty that's why.
|
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.