将模型传递给视图然后再从视图传递给控制器

时间:2012-02-01 08:23:42

标签: asp.net-mvc asp.net-mvc-3 model-view-controller

我对asp.net mvc相当新,我有一个问题。示例模型:

public class FooModel
{
 public string StrA {get; set;}
 public string StrB {get; set;}
}

我怎样才能做到这样:将模型传递给视图(模型填充StrA,StrB为空),更新模型的StrB(StrA填充,StrB填充),然后将其提交给我的操作,同时填充StrA和StrB (默认情况下,我将传递新的模型实例,只填充StrB,我之前的StrA值将会消失。)

我知道我可以使用HiddenFor,但还有其他方法吗?

2 个答案:

答案 0 :(得分:2)

  

我知道我可以使用HiddenFor,但还有其他方法吗?

在您的POST操作中,您可以从您在GET操作中获取它的同一位置获取StrA属性的值。这样您就不需要使用隐藏字段来保留它。

例如:

public ActionResult Index()
{
    var model = new FooModel
    {
        StrA = PopulateStrAFromSomewhere()
    };
    return View(model);
}

[HttpPost]
public ActionResult Index(string strB)
{
    var model = new FooModel
    {
        StrA = PopulateStrAFromSomewhere(),
        StrB = strB
    }

    ... do something with the model
}

现在在视图中,您只能在表单中包含StrB的输入字段,以允许用户修改其值:

@model FooModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.StrB)
    @Html.EditorFor(x => x.StrB)
    <button type="submit">OK</button>
} 

答案 1 :(得分:0)

您可以使用例如构建自己的POST jQuery AJAX(http://api.jquery.com/jQuery.post/)或手动构建表单并提交它(http://api.jquery.com/submit/)。这意味着您不必在页面上创建可见的表单(如果这是您想要避免的)。

但是,您需要将数据传递给DOM并以某种方式保留它(例如,使用隐藏字段)。由于HTML是无状态的,如果你真的想以某种方式将它恢复到服务器,你不能神奇地将StrA保存在某处 - 除非它不是要在请求之间进行更改,这意味着你不需要将它传递给客户端并返回任何方式(请参阅Darin的回复,了解在这种情况下如何处理它)。