Note that there are some explanatory texts on larger screens.

plurals
  1. POPosting Complex Object through Ajax to MVC
    primarykey
    data
    text
    <p>I have been fiddling with MVC for quite some time now and I'm interested in creating a mini-application that records all cd-contents under one cd. My main hurdle for now is how can I pass on a list of Contents to a Cd.class along with other property values?</p> <pre><code>public class Cd { public int CdId { get; set; } public string Description { get; set; } public virtual ICollection&lt;Content&gt; Contents { get; set; } } public class Content { public int Id { get; set; } public string Name { get; set; } public string ContentType { get; set; } } </code></pre> <p>View:</p> <pre><code> $.ajax({ url: '/cd/addCd', type: 'POST', data:$('form').serialize() }); @using(Html.BeginForm()){ @Html.LabelFor(x=&gt;x.CdId) @Html.TextBoxFor(x=&gt;x.CdId) &lt;br/&gt; @Html.LabelFor(x=&gt;x.Description) @Html.TextBoxFor(x=&gt;x.Description)&lt;br /&gt; &lt;input type="submit" value="Submit" id="submit"/&gt; </code></pre> <p>}</p> <p>Please do note that the CdId and Description values are already passed on by the Serialize function of ajax - only the Contents property is the one I'm having trouble grasping the idea</p> <p><strong>Update</strong></p> <p>I solved my query by creating an ajax snippet that sends the serialized data to the controller:</p> <pre><code> $.ajax({ type: 'POST', url: 'http://localhost:54004/Cd/AddCd', data: JSON.stringify(formData), contentType:'application/json;charset=utf-8' }) .success(function () { }) </code></pre> <p><strong>With the following formData obj:</strong></p> <pre><code> var formData = { 'Description': "Learning Visual Studio 2012", 'CdId': 1, 'Contents': [{ "Id": 1, "Name": "Video #1", "ContentType": "Mp4" }, { "Id": 2, "Name": "Video #2", "ContentType": "Mp4" }] }; </code></pre> <p>Now the controller is now receiving the full set of Cd entity value along with its Content. Hope this could serve useful to someone in the future.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload