asp.net mvc 4 - Display selected value from listbox (MVC) -


i have database, consists of table "jobs": job_id (int, primary key), job_nm (nchar(50)). in "model" folder add ado.net entity data model.

controller is:

namespace listbox_proj.controllers {     public class homecontroller : controller     {         mydbentities1 db = new mydbentities1();          [httpget]         public actionresult index()`enter code here`         {             var jobs = db.jobs;              viewbag.jobs = jobs;                                  return view(jobs);         }          [httppost]         public actionresult index(string sel1)         {             viewbag.result = sel1;              return view();         }             } }     

view is:

@{     viewbag.title = "index"; }  <html>     <head>          <meta name="viewport" content="width=device-width"/>         <title>index</title>              </head>      <body>             <h1 class="label">please, select job interested in:</h1> <br /><br />              <select name="sel1" id ="sel1">                 <option>all</option>                 @foreach (var j in viewbag.jobs)                 {                     <option><p>@j.job_nm</p></option>                 }             </select>           <form action="/home/index" method="post">             <input type="submit" value ="search">                     <input type="text">@viewbag.result</input>         </form>      </body> </html> 

but when choose item in selectbox, , push "search", have error message:

![enter image description here][1]

message in english - object reference not set instance of object.

please, me! wrong? how can correct it?

you have 2 issues here.

the first viewbag.jobs being populated on [httpget]; need ensure viewbag populated in [httppost]. better solution use proper view model - example,

public class jobviewmodel {     public jobs jobslist { get; set; }     public string result { get; set; } } 

simply populate in both [httpget] , [httppost] procedures, , pass view() call. add:

@model jobsviewmodel 

at top of view allow access through (strongly-typed) model.jobslist property.

a secondary issue you'll come across sel isn't being submitted, falls outside of <form> tags - remember, information submitted in form contained within it.

restructure view to:

    <form action="/home/index" method="post">         <select name="sel1" id ="sel1">             <option>all</option>             @foreach (var j in model.jobslist)             {                 <option><p>@j.job_nm</p></option>             }         </select>          <input type="submit" value ="search">                 <input type="text">@model.result</input>     </form> 

and problem should solved.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -