如何在没有数据丢失的情况下重定向到同一视图 [英] How can we redirect to same view without data loss
本文介绍了如何在没有数据丢失的情况下重定向到同一视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我第一次加载时,我在项目上的同一视图上有两个文本框我们使用model.name在控制器上提供文本框的值它在视图中显示比我点击按钮另一个文本框显示其他值model.age但是model.name值是删除我想要文本框中的两个值
我尝试过:
I have two textbox on same view on project when I first time load we provide value on textbox from controller using model.name its show in view than i click on button another textbox show other value model.age but the model.name value is remove I want both the values in textbox
What I have tried:
<pre>namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
// GET: Home
Class1 cs = new Class1();
public ActionResult Index()
{
if(TempData["A"]==null)
{
cs.name = "hi";
TempData["A"] = "B";
}
return View(cs);
}
public ActionResult A()
{
cs.age ="hello";
//return RedirectToAction("Index",cs);
return View("Index", cs);
}
}
}
推荐答案
我相信你的观点: -
你必须在每个请求上绑定你的模型以保持其价值。
您的代码如下: -
I am sure about your view : -
you have to bind back your model on each request to preserve its value.
Your code would be something like:-
Home Controller
public class HomeController : Controller
{
Class1 cs = new Class1();
[HttpGet]
public ActionResult Index(Class1 model)
{
cs.name = "hi";
if (TempData["A"] == null)
{
TempData["A"] = "B";
}
return View(cs);
}
public ActionResult A(Class1 model)
{
model.age = "hello";
return RedirectToAction("Index", model);
//return View("Index", cs);
}
}
Index View
<pre>@using Articles.Models
@model Class1
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("A", "Home", FormMethod.Post))
{
<div>
@Html.LabelFor(model => model.name)
@Html.EditorFor(model => model.name)
<br />
@Html.LabelFor(model => model.age)
@Html.EditorFor(model => model.age)
</div>
<div class="options">
<input type="submit" name="save" class="btn btn-success" value="Save" />
</div>
}
</body>
</html>
您需要切换到模型驱动的UI。 UI的两端都可以操作模型并从中获取数据以显示它。
=>创建数据模型类并处理其更改并在UI中显示
You need to switch to a model driven UI. Both ends of your UI can manipulate the model and fetch data from it to display it.
=> Create a data model class and handle its changes and display in the UI
这篇关于如何在没有数据丢失的情况下重定向到同一视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文