将返回值从actionresult转移到另一个视图

时间:2013-07-25 06:00:36

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我试图在视图中的标签中显示数据,数据来自另一个视图,为此我已经这样做了

这是我的模型

namespace MvcSampleApplication.Models
{
    public class products
    {
        [Required]
        [Display(Name = "Textbox1")]
        public string EnteredValue { get; set; }
    }    
    public class category
    {
        [Display(Name = "Label1")]
        public string lablvalue { get; set; }        
    }
}

这是我的控制器

namespace MvcSampleApplication.Controllers
{
    public class EnterValueController : Controller
    {           
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Valuesadd(MvcSampleApplication.Models.products model)
        {
            return View(model);            
        }
        [HttpPost]
        public ActionResult SubmitValue(MvcSampleApplication.Models.products model)
        {
            ViewData["logindata"] = model.EnteredValue;    
            return View("submittedvalues");               
        }                
        public ActionResult submittedvalues()
        {
            var model = new MvcSampleApplication.Models.category();
            string data = ViewData["logindata"] != null ? ViewData["logindata"].ToString() : "";
            model.lablvalue = data;
            return View(model);            
        }
    }
}

和我的观点

@model MvcSampleApplication.Models.category
@{
    ViewBag.Title = "submittedvalues";
}
<h2>submittedvalues</h2>
@using (Html.BeginForm())
{
    <div>
        <fieldset>
          <legend>
              Lable value
          </legend>                
            @Html.DisplayFor(s=>s.lablvalue)         
        </fieldset>
    </div>
} 

当我按下提交按钮时,它将查看(submittedvalues.cshtml)但不显示结果 非常感谢....

2 个答案:

答案 0 :(得分:6)

将代码更改为,而不是return View()使用RedirectToAction将其重定向到其他操作。另请注意,我使用的是TempData而不是ViewData

[HttpPost]
public ActionResult SubmitValue(MvcSampleApplication.Models.products model)
{
    TempData["logindata"] = model.EnteredValue;    
    return RedirectToAction("submittedvalues");               
}                
public ActionResult submittedvalues()
{
    var model = new MvcSampleApplication.Models.category();
    string data = string.IsNullOrEmpty(TempData["logindata"]) ? string.Empty : TempData["logindata"].ToString();
    model.lablvalue = data;
    return View(model);            
}

答案 1 :(得分:0)

那是因为:

return View("submittedvalues"); 

立即呈现名为“submittedvalues.cshtml”的视图

所以这段代码:

public ActionResult submittedvalues()
        {
            var model = new MvcSampleApplication.Models.category();
            string data = ViewData["logindata"] != null ? ViewData["logindata"].ToString() : "";
            model.lablvalue = data;
            return View(model);            
        }