【问题标题】:How to Update the Model in MVC 5如何在 MVC 5 中更新模型
【发布时间】:2018-06-05 09:40:32
【问题描述】:

我的 MVC 5 应用程序中有一个 Markdown 编辑器。代码如下:

<script type="text/javascript">
var executivesummary = new tui.Editor({
el: document.querySelector('#Recommendation'),
previewStyle: 'vertical'})

我有保存功能,可以像这样保存编辑器的内容

function saveContent(e) {
 var contents = Recommendation.GetValue();
 console.log(content)
 e.preventDefault();
                        }

我在模型中有一个带有 get 和 set 的字段,我想将此值“内容”更新到模型。如何做到这一点?

【问题讨论】:

  • 您的意思是要将值保存到服务器/数据库?或者您想简单地在 HTML 页面中更新它而不保存?这并不完全清楚。将其保存到“模型”没有多大意义——模型类是一个短暂的对象,仅用于将数据从控制器传输到视图并再次返回。它是发送数据的结构,而不是数据的目的地。无论哪种方式,这是一项常见的任务,有许多可能的解决方案,并且可能已经有很多关于该主题的在线内容。您已经研究或尝试过什么?
  • @ADyson 是的!我想将“内容”中包含的值更新到数据库。而在其他情况下,我会使用像 @Html.TextAreaFor(model =&gt; model.WORecommendation, new { htmlAttributes = new { @class = "form-control" } }) 这样的 Html 助手。有没有办法更新到数据库?
  • 我的建议可能是发出 ajax 请求并将 contents 的值传递给数据中的服务器
  • @ADyson 谢谢!

标签: javascript asp.net asp.net-mvc asp.net-mvc-partialview


【解决方案1】:

您需要调用控制器中的操作方法来更新模型。然后您可以使用 Ajax(或使用 Ajax.BeginForm)重新加载视图(或部分视图)。

一些示例 ajax 调用:

$("#idToClickOn").click(function () {
    var contents = @Html.Raw(Json.Encode(Recommendation.GetValue()));
    $.ajax({
        url: 'https://@(Request.Url.Host)/Controller/Action',
        type: 'POST',
        dataType: 'json',
        data: contents,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
        }
        error: function (data) {
            alert("error: " + data);
        }
    });
});

Ajax.BeginForm 的一些例子:

@using (Ajax.BeginForm("Action", new { Controller = "ControllerName", area = "" }, new AjaxOptions() { OnSuccess = "onSuccessLogin", HttpMethod = "POST", UpdateTargetId = "idInViewToUpdate"}, new { id = "formID" }))
{
    ...
    <div>
        @Html.Partial("Path to form body")                           
    </div>
    <button class="btn btn-primary btn-block">Save</button>
}

您的控制器,例如:

[HttpPost]
[ValidateAntiForgeryToken]
[HandleError]
public ActionResult Action(YourModel model)
{
    if (ModelState.IsValid)
    {
        do Something;
        return PartialView("Path to your view");
    }
    else
    {
        return PartialView("Path to your view", model);
    }
}

当然,YourModel 需要适合您创建的 json。

在该操作中,您可以修改模型并重新加载视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2013-01-21
    • 2012-08-29
    • 1970-01-01
    • 2015-03-05
    • 2012-08-04
    相关资源
    最近更新 更多