Persist data through POST with multiple forms

I was wondering what is the best way to approach this issue in ASP.NET MVC. The following is a trivial example of what I would like to do:

I have a webpage with a text box and a submit button. When the submit button is clicked, I want the content to appear on the same web page. When it is pressed again, I would like it to be displayed in the first part presented, as well as new data that has just been sent.

I tried to save this data in the model, but the model is cleared every time messages are in the form. How can I do this and save the data from the message to the last (and the message before)?

+3
source share
2 answers

, , "TempData". TempData , .

ViewModel:

    public class SomeClass
    {
        public string Something { get; set; }
        public List<string> RetainedValues { get; set; } 
    }

:

    [HttpGet]
    public ActionResult Index()
    {
        return View("Index");
    }

    [HttpPost]
    public ActionResult Index(SomeClass postedValues)
    {
        // retrieve retained values
        var retained = (List<string>) TempData["RetainedValues"] ?? new List<string>();
        retained.Add(postedValues.Something);

        // save for next post
        TempData["RetainedValues"] = retained;

        // setup viewmodel
        var model = new SomeClass
        {
            RetainedValues = retained
        };

        return View("Index", model);
    }

( ):

    <div>
        @foreach(var item in Model.RetainedValues)
        {
            <div>@item</div>
        }
    </div>
    @using(Html.BeginForm())
    {
        @Html.EditorFor(m=>m.Something)
        <input type="submit"/>
    }
+3

, .

: @Html.HiddenFor(model => model.YourProperty)

, , : one newValue , allValues.

allValues ​​ , . newValue allValues.

- :  model.allValues ​​+ = newValue;

- UPDATE

tempdata, @Jesse

, , , .

+1

All Articles