将更改保存到DB MVC [英] Saving changes to the DB MVC

查看:87
本文介绍了将更改保存到DB MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将一些数据保存到数据库时遇到问题.我可以在JS函数中看到ID和Date返回适当的值...但是,控制器类中Process函数的参数仍然为null.我不知道为什么会这样. Hello模型中还包含一个linq查询,但由于没有必要,所以没有包含它.

I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.

型号:

 public class Hello
    {
        List<string> Ids { get; set; }

        List<string> Dates { get; set; }
    }

控制器:

   [HttpPost]
    public ActionResult Process(string ids, string dates) 
    {
        Hello model = new Hello();
        if (ModelState.IsValid)
        {

            using (db = new DB())
            {

                rp = new RequestProcess();
                //var c = rp.getHello(model, dates);
                var c = rp.getStuff();

                if (c != null)
                {
                    foreach (var i in c)
                    {
                        if (i != null)
                        {
                            ids = i.ID;
                            dates = i.Date.ToString();
                        }
                        db.SaveChanges();
                    }

                }

            }
            ViewBag.Message = "Success";
            return View(model);
        }
        else
        {
            ViewBag.Message = "Failed";
            return View(model);
        }
    }

查看:

  <td><input class="id" type="checkbox" id=@item.ID /></td>
  <td>@Html.DisplayFor(x => @item.ID)</td>
  <td><input class="date" id=date@item.ID type="text" value='@item.Date'/></td>

  $(document).ready(function () {
        var ids = "";
        var dates = "";
        $("#btnSubmit").bind("click", function () {
            createUpdateArrays();
            var url = "/Sample/Process";
            $.ajax({
                type: "POST",
                url: url,
                data: { ids: ids, dates: dates },
                contentType: 'application/json; charset=utf-8',
                success: function (success) {
                    if (success === true) {
                        alert("HERE WE ARE");
                    }
                    else {
                        alert("eror");
                    }
                }
            });
            ids = "";
            dates = "";
        });
        function createUpdateArrays() {
            var i = 0;
            $('input.remedy-id:checkbox').each(function () {
                if ($(this).is(':checked')) {
                    var rid = $(this).attr("id");
                    $('.planned-date').each(function () {
                        var did = $(this).attr("id");
                        if (did === rid) {
                            var date = $(this).val();
                            ids += rid + ",";
                            dates += date + ",";
                        }
                    });
                };
            });
        };

任何帮助将不胜感激!

Any help would be appreciated!

推荐答案

您的代码中存在几个问题:

There are several issues in your code:

1)您正在传递包含viewmodel属性的JSON字符串,有必要在AJAX回调中设置contentType: 'application/json; charset=utf-8'选项,以确保模型绑定程序将其识别为viewmodel参数.

1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.

2)return View()不适用于AJAX响应,请改用return PartialView()并将html()呈现在目标元素中.

2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.

因此,您应该使用以下提供的AJAX设置:

Therefore, you should use AJAX setup as provided below:

$.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(list),
    contentType: 'application/json; charset=utf-8',
    success: function (result) {
        $('#targetElement').html(result);
    },
    error: function (xhr, status, err) {
        // error handling
    }
});

控制器操作

[HttpPost]
public ActionResult Process(Hello model) 
{
    if (ModelState.IsValid)
    {
        using (db = new DB())
        {
            // save data
        }
        ViewBag.Message = "Success";
        return PartialView("_PartialViewName", model);
    }
    else
    {
        ViewBag.Message = "Failed";
        return PartialView("_PartialViewName", model);
    }
}

请记住,AJAX回调旨在更新某些HTML元素而不重新加载整个视图页面.如果您想用已提交的结果重新加载页面,请改用普通表单提交(Html.BeginForm()).

Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).

这篇关于将更改保存到DB MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆