【问题标题】:mvc display text after post and keep data in formmvc 在发布后显示文本并将数据保存在表单中
【发布时间】:2016-11-29 14:05:19
【问题描述】:

在我的 mvc 页面中发布表单后如何显示消息并将添加/选择的数据保留在表单中?我试图渲染一个局部视图,但它会渲染一个只包含实际局部视图的空白页面。

<div id="resultTarget">
    @Html.Partial("CalculationResult", new Model.CalculatedPrice())
</div>

[HttpPost]
public PartialViewResult GetPrice(FormCollection formCollection)
{
    // This renders only the partialview
    return PartialView("CalculationResult", model);
} 

【问题讨论】:

  • 那么我会在 GetPrice 中返回什么?如果我只使用 return View();我收到一条错误消息,告诉我“未找到视图 'GetPrice' 或其主视图,或者没有视图引擎支持搜索的位置”
  • [HttpPost] public PartialViewResult GetPrice(FormCollection formCollection) { ViewBag.Test = "message"; return PartialView("CalculationResult", model); } 然后在您的“CalculationResult”视图中.. 将@ViewBag.Test 放在您想要消息去的任何地方
  • 当我尝试显示实际的 viewbag 消息后,我会进入一个空白页面。这不可能,...
  • 好的,那么问题是您可以在CalculationResult视图中访问Viewbag..但是数据不存在?
  • viewbag 消息显示在页面上,但这是唯一显示的内容,从一开始的所有其他内容(表单、表单字段、图像等)都消失了..

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


【解决方案1】:

如果您使用表单发布重新加载页面,数据将会丢失。创建视图模型并使用@Html.TextBoxFor()@Html.ListBoxFor() 等将控件绑定到特定属性。

现在不是将表单提交回控制器,而是使用 javascript 在按钮单击功能上将数据发布回控制器。

见以下代码:

在按钮点击功能中:

var modelObj = {};
modelObj.prop1 = $('#txtField1').val();
modelObj.prop2 = $('#txtField2').val();
var postObj = JSON.stringify(modelObj); // convert object to json

$.ajax({
type: "POST",
traditional: true,
dataType: "json",
url: "/SomeController/GetPrice",
data: { formCollection: postObj }
cache: false,
success: function (data) {
    if (data) {
        //Some Code if post success
    }
    else {
        // Some code if post failed
    }
}});

在 SomeController 中:

[HttpPost]
public JSonResult GetPrice(FormCollection formCollection)
{
// Do your action with the formCollection object here
// if(action.success)
   {
        return JSon(true);
   }
   return JSon(false);
} 

这样您可以防止重新加载页面并将数据保留在表单中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2022-11-13
    相关资源
    最近更新 更多