c# - Saving data from a html form to List -


i have 2 create methods 1 decorated httpget, , other httppost. have create view first 1 looking :

@{    viewbag.title = "create"; }  <h2>create</h2>  <form action="/" method="post">     <input type="text" name="txt" value="" />     <input type="submit" />    </form> 

the methods :

list<string> mylist = new list<string> { "element1", "element2", "element3" }; public actionresult create()     {         return view();     }      [httppost]     public actionresult create(string txt)     {         //mylist.add(request.form["txt"]);         mylist.add(txt);         return view();     } 

i simly trying pass data form on button second create() , save mylist.

i need advice on how make work.

once you've fixed form (in you're posting application's default route (by default homecontroller.index() method) sending request /, instead of create method), correctly adding value list. problem is, value stays current request.

to make things persistent, need consider persistence layer in memory, in database, or in session. i've provided full sample below uses session, give per-user list instance. without layer, controller being routinely disposed of once action has completed processing, , amends list not persisted. normal request lifecycle in asp.net , makes sense when consider app ever dealing 1 request @ time. it's important note making static isn't form of persistence per-se, in lifetime , reliability indeterminable. appear work, once application pool recycles (ie. app destroyed , reloaded in memory) have again lost amends list.

i suggest read on session state understand going on below. in nutshell, each application user / unique visitor site given unique 'session id', can use session id store data wish use on server side. why, if visit create method separate browsers (or try private mode) maintaining 2 separate lists of data.

view (which outputs list user):

@model list<string> @{     viewbag.title = "create"; }  <h2>create</h2>  <ul>     @foreach(var str in model)     {         <li>@str</li>     } </ul>  @using (html.beginform()) {     <input type="text" name="txt" />     <input type="submit" /> } 

controller contents:

public list<string> mylist {         {         return (list<string>)(             // return list if exists in session             session[nameof(mylist)] ??             // or create default values             (session[nameof(mylist)] = new list<string> { "element1", "element2", "element3" }));     }     set     {         session[nameof(mylist)] = value;     } }  public actionresult create() {     return view(mylist); }  [httppost] public actionresult create(string txt) {     mylist.add(txt);     return view(mylist); } 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -