【问题标题】:How to move data from one action to another action in the same controller for forms?如何在表单的同一控制器中将数据从一个动作移动到另一个动作?
【发布时间】:2021-01-09 16:47:38
【问题描述】:

如何将数据从 Iactionresult 移动到另一个 action result?我一直在尝试显示表单中的数据并查看另一个 Iactionresult?我尝试使用 Tempdata,但似乎有错误。谁能帮帮我?

当我单击特定 ID 时,此操作会显示单个产品详细信息。

  [HttpGet]
  public IActionResult Details(int id)
  {
     string sql = String.Format(@"SELECT * FROM WBProduct 
                                   WHERE Id = {0}", id);
     List<Product> lstProduct = DBUtl.GetList<Product>(sql);
     if (lstProduct.Count == 0)
     {
        TempData["Message"] = $"Product #{id} not found";
        TempData["MsgType"] = "warning";
        return RedirectToAction("Index");
     }
     else
     {
        
        Product cdd = lstProduct[0];

        return View(cdd);
     }

        

  }

我想在这个 IActionResult 中显示产品的详细信息

[HttpPost]
public IActionResult Create()
{
     return View("Create");
}

查看详情:

@model Product

<div>

    <div class="form-group row">
        <div class="offset-sm-2"><h2>@Model.ProductName</h2></div>
    </div>

    <div class="form-group row">
        <div class="offset-sm-2 col-sm-5">
            <img id="ImgPhoto" src="~/images/product/@Model.ProductImage" style="width:400px;" />
        </div>
    </div>

    <div class="form-group row">
        <label class="control-label col-sm-2" for="City">Weight: </label>
        <div class="col-sm-5">
            <input type="text" asp-for="ProductWeight" class="form-control" readonly />
        </div>
    </div>

    <div class="form-group row">
        <label class="control-label col-sm-2" for="Date">Stock :</label>
        <div class="col-sm-5">
            <input type="text" asp-for="ProductStock" class="form-control" readonly />
        </div>
    </div>



    <div class="form-group row">
        <label class="control-label col-sm-2" for="Cost">Price: </label>
        <div class="col-sm-5">
            <input type="text" asp-for="ProductPrice" asp-format="{0:C}" class="form-control" readonly />
        </div>
    </div>

    <div class="form-group row">
        <label class="control-label col-sm-2" for="Story">Description: </label>
        <div class="col-sm-5">
            <textarea asp-for="ProductDescription" rows="8" cols="20" class="form-control" readonly></textarea>
        </div>
    </div>

   
    

    <div class="form-group row">
        <a href="http://localhost:50528/Product/Create" class="btn btn-info" role="button" > Add to Cart </a>
    </div>

    </div>

创建视图:

@model Product
<div class="form-group row">
    <div class="offset-sm-2"><h2>@Model.ProductName</h2></div>
</div>



<div class="form-group row">
    <label class="control-label col-sm-2" for="City">Weight: </label>
    <div class="col-sm-5">
        <input type="text" asp-for="ProductWeight" class="form-control" readonly />
    </div>
</div>

<div class="form-group row">
    <label class="control-label col-sm-2" for="Date">Stock :</label>
    <div class="col-sm-5">
        <input type="text" asp-for="ProductStock" class="form-control" readonly />
    </div>
</div>



<div class="form-group row">
    <label class="control-label col-sm-2" for="Cost">Price: </label>
    <div class="col-sm-5">
        <input type="text" asp-for="ProductPrice" asp-format="{0:C}" class="form-control" readonly />
    </div>
</div>

<div class="form-group row">
    <label class="control-label col-sm-2" for="Story">Description: </label>
    <div class="col-sm-5">
        <textarea asp-for="ProductDescription" rows="8" cols="20" class="form-control" readonly></textarea>
    </div>
</div>

我得到的错误信息是:

【问题讨论】:

  • TempData["Product"] = lstProduct[0];
  • @Steve 它不起作用。它没有显示产品的个人详细信息,因此数据不会传输到视图
  • 你能显示操作代码吗?至少是您阅读和使用 TempData 的一些相关部分?
  • 我已粘贴视图以获取详细信息
  • 等等。您正在尝试重定向到 POST 操作?如果我没有错,这是不可能的。您应该重定向到 GET 操作

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


【解决方案1】:

这应该是 GET 操作,而不是 POST 操作,然后您应该从 TempData 中提取信息并将其作为参数传递给视图 cshtml。

 TempData["Product"] = JsonConvert.SerializeObject(lstProduct[0]);
 return RedirectToAction("Create");

现在您可以在 Create 操作中反序列化并检索您的产品

[HttpGet]
public IActionResult Create()
{
     // If the caller has prepared a product we can show it.
     if(TempData.ContainsKey("Product"))
     {
         Product p = JsonConvert.DeserializeObject<Product>(TempData["Product"]);
         return View(p);
     }
     else
         return View();
}

【讨论】:

  • 我已经编辑了代码,因为它只能在我包含 '{ Product cdd = lstProduct[0]; 时显示产品返回视图(cdd); }' 如何包含 TempData?
  • stackoverflow.com/questions/34638823/… 可以找到一个更好的可重用代码示例
【解决方案2】:

如果你想将数据从一个动作移动到同一个控制器中的另一个动作 只需从另一个动作调用一个动作并将数据作为另一个动作的输入参数。

要将消息发送到索引操作,首先为消息创建一个类:

public class ErrorMsg
{
 public string Message {get; set;}
 public string MessageType {get; set;}
}

将您的操作索引更改为:

public IActionResult Index(ErrorMsg errorMsg)
  {
// if action called from another controller action, details for exapmple,
//errorMsg will contain data from that action
// otherwise errMsg will be an empty default object with empty strings

 //Check if error
if(!string.IsNullOrEmpty(errorMsg.Message) ...your error code
  else       ....your index code here
}

更改您的操作详情代码:

  public IActionResult Details(int id)
  {
     string sql = String.Format(@"SELECT * FROM WBProduct 
                                   WHERE Id = {0}", id);
     List<Product> lstProduct = DBUtl.GetList<Product>(sql);

     if (lstProduct.Count == 0)
     {
        var errMsg = new ErrMessage { 
        Message = $"Product #{id} not found",
        MessageType = "warning"
         }

        return Index(errMsg);
     }
     else
     {
       
       Product cdd= lstProduct.FirstOrDefault();
       //Or you can try again  var  cdd = lstProduct[0]; if you like it more

        return View("Details", cdd);
     }
  }

将您的创建操作更改为:


public IActionResult Create(Product product)
{

// if action called from another controller action, "product" will contain data //from that action
// otherwise "product" will be posted from the view or it will be an empty model with the default value fields

 if(product.Id ==0)  ... call add ef code 
    else ... call update ef code
}

你必须在所有视图中添加

@model Product

@using (Html.BeginForm("Create", "Product", FormMethod.Post)
{
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

<div>

<input type="hidden" asp-for="@Model.Id" />

    <div class="form-group row">
        <div class="offset-sm-2"><h2>@Model.ProductName</h2></div>
    </div>

    <div class="form-group row">
        <div class="offset-sm-2 col-sm-5">
            <img id="ImgPhoto" src="~/images/product/@Model.ProductImage" style="width:400px;" />
        </div>
    </div>

    <div class="form-group row">
        <label class="control-label col-sm-2" for="City">Weight: </label>
        <div class="col-sm-5">
            <input type="text" asp-for="ProductWeight" class="form-control" readonly />
        </div>
    </div>

    <div class="form-group row">
        <label class="control-label col-sm-2" for="ProductStock">Stock :</label>
        <div class="col-sm-5">
            <input type="text" asp-for="ProductStock" class="form-control" readonly />
        </div>
    </div>



    <div class="form-group row">
        <label class="control-label col-sm-2" for="ProductPrice">Price: </label>
        <div class="col-sm-5">
            <input type="text" asp-for="ProductPrice" asp-format="{0:C}" class="form-control" readonly />
        </div>
    </div>

    <div class="form-group row">
        <label class="control-label col-sm-2" for="ProductDescription">Description: </label>
        <div class="col-sm-5">
            <textarea asp-for="ProductDescription" rows="8" cols="20" class="form-control" readonly></textarea>
        </div>
    </div>

    <div class="form-group row">
        <button class="btn btn-info btn-link" type="submit"> Add to Cart </button>
    </div>

    </div>  
}

【讨论】:

  • 对不起,我不明白要达到什么目的。
  • 我在上面的问题中编辑了我的代码。您建议的代码会返回一条错误消息,因为它可以找到特定的产品详细信息。使用新编辑的代码,我如何调用移动数据? @Sergey
  • 我看到了您的详细信息视图,但我没有看到任何表格。所以我想知道当你点击链接时数据会去哪里?根据它应该创建的href。您是想将模型细节移回细节还是创建?什么时候需要将数据从一项操作转移到另一项操作?
  • 我正在尝试将数据从详细信息操作移动到创建操作。
  • @iwanttopassmyfyp 我不明白你为什么需要它。如果未找到产品,您只需将空产品作为模型返回查看详细信息,否则查看详细信息字段将使用产品值初始化。你能展示你的创建视图吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
  • 2017-09-18
  • 1970-01-01
  • 2018-03-18
相关资源
最近更新 更多