I'm trying to post data to controller using ajax post it contains a model and string,the string value comes to the controller but the model is always null.Can anyone help.Attaching the code
<script>
function save() {
var st = "Test";
var source = ({
'Name': $('#Name').val(),
'Code': $('#Code').val(),
'Address': $('#Address').val(),
'City': $('#City').val(),
'State': $('#State').val(),
'Country': $('#Country').val(),
'Phone': $('#Phone').val(),
'Fax':$('#Fax').val()
});
$.ajax({
type: "POST",
url:'@Url.Action("Save", "Hospitals")',
data: { 'st': st, 'hospital': source }
});
}
Controller
public ActionResult Save(string st,Hospital hospital)
{
if (ModelState.IsValid)
{
db.Hospitals.Add(hospital);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
var dept = db.Departments.ToList();
ViewBag.department = dept;
}
return View(hospital);
}
Usedata: { 'st': st, 'hospital': JSON.stringify(source) }
This will convert the variable to be interpretable by the model class in your action method
Jquery
<script>
function save() {
var cval;
var str = "";
$(".chkmaincat:checked").each(function (i) {
cval = $(this).val();
str = str + cval + ",";
});
alert(str);
var source =
{
'Name': $('#Name').val(),
'Code': $('#Code').val(),
'Address': $('#Address').val(),
'City': +$('#City').val(),
'State': $('#State').val(),
'City': $('#City').val(),
'Country': $('#Country').val(),
'Phone': $('#Phone').val(),
'Fax': $('#Fax').val()
}
$.ajax({
type: "POST",
url: '/Hospitals/Save?st='+str,
data: source
});
}
Controller
public ActionResult Save(string st,Hospital hospital)
{
if (ModelState.IsValid)
{
db.Hospitals.Add(hospital);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
var dept = db.Departments.ToList();
ViewBag.department = dept;
}
return View(hospital);
}
by doing the above i'm able to get the string value as well as the modal object.Thanks for all the help.