Ajax posting in mvc



我试图使用ajax post数据到控制器,它包含一个模型和字符串,字符串值来到控制器,但模型总是空的。有人能帮忙吗?附加代码

<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 }
    });
}

控制器

 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);
    }

使用
data: { 'st': st, 'hospital': JSON.stringify(source) }

这会将变量转换为可由动作方法中的模型类解释的

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
    });
}

控制器

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);
    }

通过上述操作,我能够获得字符串值以及模态对象。谢谢你的帮助。

最新更新