Reputation: 1198
Hi I have a view in which I wrote a jquery script to pass a html table values into a JSON object as shown below;
var contactData = [];
$('#tblContacts > tbody > tr').each(function () {
contactData.push({
firstName: $(this).find('input.c-firstname').val(),
lastname: $(this).find('input.c-lastname').val(),
phone: $(this).find('input.c-phone').val(),
email: $(this).find('input.c-email').val()
})
})
Though I left out part of the code above, but I confirmed that contactData
object has the required data. So I got no issues there.
My Challenge: Now I need the object contactData
passed into my controller method to get the values into the database as shown below;
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(CreateBusinessPartnerVM businessPartnerVM)
{
if (ModelState.IsValid)
{
var businessPartner = new BusinessPartner
{
CardCode = prefixCardCode + businessPartnerVM.CardName.ElementAt(0) + DateTime.Now.ToString(),
CardName = businessPartnerVM.CardName,
CardType = businessPartnerVM.CardType,
Email = businessPartnerVM.Email,
Phone = businessPartnerVM.Phone,
IsActive = businessPartnerVM.IsActive,
ContactPersons = //contactData from the jquery script in the view
};
}
}
I have searched and still not found something similar with my requirement. I hope to get a fast help here. Thanks.
Upvotes: 0
Views: 483
Reputation: 537
Based on your code i guess your are using a form to submit data to your controller. If so you can add the data to a hidden input type.
Check with your chrome inspector the id of the hidden field and add the data like this
$('#hiddenFieldId').val(contactData);
Upvotes: 1
Reputation: 392
You need to edit your CreateBusinessPartnerVM model.
Add a new property that is the array of ContactData object. This way you can post contact data in the same model for business partner and process it further.
somewhat like this;
public class CreateBusinessPartnerVM {
.... other properties...
public ContactData[] ContactList { get; set; }
}
public class ContactData {
public string FirstName {get; set;}
public string LastName {get; set;}
public string Phone {get; set;}
public string Email {get; set;}
}
Once this is up, you can pass the js contactData object along the main object that is being submitted.
* New Edit*
I see your table already has input fields. You just need to do 2 things to submit Contact Data
Just make sure you use names of fields right and also their case.
Upvotes: 1