Model with child collections in ASP.NET MVC 3

I am trying to learn ASP.NET MVC 3 based on the background of web forms. I am trying to figure out what the MVC method will be for implementing what I want, and it's really difficult that I'm not sure what to do on Google!

What I cannot understand is to work with more complex models. All the tutorials on asp.net work around fairly simple data objects and, therefore, pretty simple editors to manage data with them.

Imagine a hypothetical application model for filing an application: -

public class Party
{
    public string PartyName {get; set;}
    public DateTime PartyDate {get; set; }

    public ICollection <Guest> Guests {get; set;}
}

public class Guest
{
    public string Name {get; set;}
    public string EmailAddress {get; set;}
}

The key here is gathering guests.

, , , - + , , ( / ajax).

- asp.net UpdatePanel. , MVC.

- , , , ,

slip

+3
3

jQuery ajax .

1) . " ", "", m ( JQuery UI ), , ajax. , jquery

2) Inpage " ", , ( javascript ), , jQuery ajax post. json. ViewModel,

HTML

<a href="#" id="addNew"> Add Guest</a>

<div id="divForm" style="display:none">
    <input type="text" id="txtName" />
    <input type="text" id="txtEmail" />
    <input type="button" id="btnSaveGuest" value="Save"/>
</div>
<ul>

<div id="divGuests"></div>  

script

$(function(){
  //Show the hidden form
  $("#addNew").click(function(){
      $("#divForm").fadeIn(300);
  }); 

   //Save the new guest details
   $("#btnSaveGuest").click(function() {
     var name=$("#txtName").val();
     var email=$("#txtEmail").val();
     $.ajax({
        url: '@Url.Action("SaveGuest","Guest")',
        data: {Name: name, EmailAddress :email},
       success: function(data) {

        if(data=="true")
        {
          //Saved successfully.May be append to list of Guest
          $("#divGuests").append("<p>"+name+"</p>");
        }
        else
        {
          //Error. Show msg to user
        }
       }
     });
   });
});

Action

[HttpPost]
public ActionResult SaveGuest(Guest objGuest)
{
  try
  {
  // read the objGuest property values and Save to db

   return "true";
  }
  catch(Exception e)
  {
     //Log error
     return "false";
  }
}

: http://jsfiddle.net/Qzk3F/16/ ( )

+2

, . Party, , . . , , . viewmodel.

, , " " .

0

public class BookingModel
{
  public Party PartyModel { get; set; }
  public Guest GuestModel { get;set; }
}

BookingModel , PartyModel, GuestModel

: , .

public class BookingModel
{
  public Party PartyModel { get; set; }
}

BookingController :

public ActionResult AddGuest(string name)
{
  BookingModel.Guests.Add(new Guest() { Name=name });
}

Obviously, you will first need a link to BookingModel. You can also create PartialView for the Guest if you want, or just use some "unrelated" inputs.

0
source

All Articles