簡體   English   中英

ViewBag中的System.Random沒有顯示為字符串?

[英]System.Random in ViewBag not displaying as string?

我要做的就是在Controller中創建一個隨機數並將其傳遞給View。 但是,當我運行該應用程序時,視圖僅顯示“ System.Random”,而不是生成的值。

這是我的控制器:

    // GET: /Products/Create
    public ActionResult Create()
    {
        Random randomID = new Random(Guid.NewGuid().GetHashCode());
        randomID.Next(20, 5000);

        ViewBag.random = randomID.ToString();

        ViewData["random"] = randomID.ToString();

        TempData["random"] = randomID.ToString();

        return View();
    }

我嘗試了ViewBag,ViewData和TempData,它們都顯示“ System.Random”。

這是我的觀點:

@model application.Models.Product

@{
    ViewBag.Title = "Create Product";
}


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.Product_ID, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.Product_ID, new { @readonly = "readonly" })

            @Html.TextBox("random", (string)@ViewBag.random, new { @readonly = true })

            @ViewBag.random

            @ViewData["random"]

            @TempData["random"]

            @Html.ValidationMessageFor(model => model.Product_ID)
        </div>
    </div>

抱歉,View有點混亂,但是我嘗試了所有可以找到的方法。 我想念什么? 我真的不想更改模型。 我嘗試了Googling幾個小時,沒有任何辦法可以解決我的問題。 這也是為產品創建隨機ID號的最簡單方法嗎? 任何幫助將不勝感激,謝謝!

Random.Next實際上返回一個值,並且根本不對Random對象進行突變。 只需在Random對象上調用ToString ,總會返回“ System.Random”(因為其他所有不覆蓋ToString類都將返回它。

您需要將生成的放在ViewBag中:

public ActionResult Create()
    {
        Random random = new Random(Guid.NewGuid().GetHashCode());
        int randomID = random.Next(20, 5000);

        ViewBag.random = randomID.ToString();   
        return View();
    }

randomId.Next()返回一個整數,您需要更多類似這樣的內容:

// GET: /Products/Create
public ActionResult Create()
{
    Random randomID = new Random(Guid.NewGuid().GetHashCode());
    int randomNumber = randomID.Next(20, 5000);

    ViewBag.random = randomNumber.ToString();

    return View();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM