Category Archives: DropDownList

DropDownList

[RESOLVED]HTTPPost model binding not working

Model

Public Class CategoriesEditViewModel
    Public Property Categories As List(Of cihCategoryOrgDef)
    Public Property Category As cihCategoryOrgDef
    Public Property lists As cihLists = New cihLists()

    Public Property SelectedItem As String
    Public Sub New()

    End Sub

    Public Sub New(codId As Guid)
        SelectedItem = codId.ToString
        lists.loadCategoryOrgDef(ZenCommon.CurrentOrgId)
        lists.loadClubWaivers(ZenCommon.CurrentOrgId)
        Categories = lists.organizationClubCategories
        Category = (From x In Categories
           Where x.codId = codId
           Select x).SingleOrDefault()
    End Sub
End Class

Controller

<HttpGet>
Function Edit(codId As Guid) As ActionResult
    Dim model As CategoriesEditViewModel = New CategoriesEditViewModel(codId)


    Return View(model)
End Function

<HttpPost>
Function Edit(category As CategoriesEditViewModel) As ActionResult

    If ModelState.IsValid Then
        'make change to DB
        Return RedirectToRoute("club_category_list")
    End If

    Return View(category)
End Function

Edit Page View

@ModelType CheckImHereMVC.CategoriesEditViewModel

@Using Html.BeginForm()
 @<fieldset>
    @Html.EditorFor(Function(m) m.Category.codDescr)

    @Html.DropDownListFor(Function(m) m.SelectedItem, New SelectList(Model.lists.organizationClubWaivers, "waiverId", "waiverName", Model.lists.organizationClubWaivers))
 

<input type="submit" value="Save" /> </fieldset>
End Using

The

HTTPGet

Edit page works fine. It goes to a url such as

categories/edit/1

and gives me the correct information corresponding to that particular Category

However, when i change some data, and click the

Save

button. i am redirected to the

HTTPPost

Edit function, however my ‘category` (value being passed in) is completely blank.

What am i doing wrong?

maylortaylor

, however my ‘category` (value being passed in) is completely blank.

Please show how the category is displayed in the View

I dont understand what you want?

I gave you my HTTPGet Controller method that creates the "Edit.html" page.

Once i run the project, go to the Edit page, the information pulls up fine on the screen. If i change the information (dropdown menu) and click the ‘save’ button. I am first redirected to the
CategoriesEditViewModel where it goes to the "Public Sub New()" empty constructor and then it goes to my HTTPPost Edit_Post ActionResult on my
CategoriesController.

Once it does get to the HTTPPost ActionResult, the value being passed in ("category As
CategoriesEditViewModel") has the following info:

Categories = Nothing

Category = nothing

Lists = nothing

SelectedItem = nothing

When Posts return "blank" stuff for fields even though the original View sent out showed something or the user changed a value….. the root cause is related to how MVC works and how the data was posted back.

  1. MVC doesn’t really pass strong typed objects back and forth, rather is passes querystrings as posts or gets.  Query strings are just Name/Value pairs…  
  2. When a post happens MVC will try to match the ActionMethod’s parameter type.  It does this by first creating a null instance of that type and then it tries to "plug" the values with the query string values posted back.  This
    means that the "Name" of the query string values becomes highly important.  If MVC cannot find the name of something in the object it creates in the query string it correctly does nothing!  No errors, nothing, it just leaves those things as they were at creation.
  3. The symptom could be "I see it in the view" but can’t see it as soon as it gets back to my controller’s action method…
  4. Solution:  take a very close look after the original view is created what names are given to the html tags and make sure your begin-form includes them on the post back.  Otherwise you will think you are "missing data".

This is the html being created for my ‘EditFor()’

<input class="text-box single-line" id="Category_codDescr" name="Category.codDescr" type="text" value="Academic" />

On the action method handling the post put a break point at first line and tell us what values are being passed in.  You should be able to locate one for Category_codDescr.  If you can’t then the form isn’t posting this back properly.

just wanted to see the html that is generated by  the

@Using Html.BeginForm()
 @<fieldset>
    @Html.EditorFor(Function(m) m.Category.codDescr)

    @Html.DropDownListFor(Function(m) m.SelectedItem, New SelectList(Model.lists.organizationClubWaivers, "waiverId", "waiverName", Model.lists.organizationClubWaivers))
 

<input type="submit" value="Save" /> </fieldset>
End Using

Also, please tell what are Request.Form collection variables in the POST Action

maylortaylor

I dont understand what you want?

I gave you my HTTPGet Controller method that creates the "Edit.html" page.

Once i run the project, go to the Edit page, the information pulls up fine on the screen. If i change the information (dropdown menu) and click the ‘save’ button. I am first redirected to the
CategoriesEditViewModel where it goes to the "Public Sub New()" empty constructor and then it goes to my HTTPPost Edit_Post ActionResult on my
CategoriesController.

Once it does get to the HTTPPost ActionResult, the value being passed in ("category As
CategoriesEditViewModel") has the following info:

Categories = Nothing

Category = nothing

Lists = nothing

SelectedItem = nothing

show the Category class. what the binder is trying to do with the post data is:

var model = new CategoriesEditViewModel();
model.Category = new cihCategoryOrgDef();
model.Category.codDescr = Request.Form["Category.codDescr"]; // will add convert to type code

[RESOLVED]Programmatic setting 'selected' in SelectListItem not rendering

This is seriously aggravating. I’ve been working with a multi-select control via the Chosen jQuery plugin. It posts values to the server I can save, no problem. The problem comes when I need to set the values of the items that were already selected, and
send that to the view for rendering – it’s not selecting the item(s).

I even set a breakpoint at my call to the Html.DropDownListFor helper to check out the values, and my chosen SelectListItem’s selected property is set to true, so all should be good. But of course it’s not. The select element is rendered without any of the
options being selected. Can anyone explain to me why a List<SelectListItem> with one or more of the items set to Selected = true would instead set none of them to true?

I actually encountered this issue fairly recently and although I don’t have the code available at hand, I remember having to rely on the rarely seen

MultiSelectList class
as opposed to the traditional SelectList to handle setting the values within the Controller :

// Set your selected values and populate your entire MultiSelectList
ViewBag.YourOptions = new MultiSelectList(YourEntireCollection, YourEntireCollection.Where(x => YourSelectedCondition));

And then within the View, I believe I didn’t rely on the DropDownListFor() Helper and simply iterated through the values in the ViewBag :

<select id='YourPropertyName' name='YourPropertyName' class='chosen-select>
    @foreach(var item in ViewBag.YourOptions)
    {
         <option value='@item.Value' @(item.Selected ? "selected" : "")>@item.Text</option>
    }
</select>

I’ll see if I can dredge up the related code sometime tomorrow, however if timing is an issue, you might consider looking through some
similar discussions like this or

this other one
, which both rely on the ListBoxFor() Helper method as opposed to the DropDownListFor().

Looks like for Chosen you need to pass the values as array

$("#dropDownId").val(["130860","130858"]);
$("#dropDownId").selectmenu('refresh');

Please take a look at this stack overflow

http://stackoverflow.com/questions/6966260/jquery-multiselect-set-a-value-as-selected-in-the-multiselect-dropdown

An example using it for Artist Tags:

View Model:

public class ArtistViewModel
{
    public Artist artist { get; set; }
    public MultiSelectList PossibleTags { get; set; }
    public int[] SelectedTags { get; set; }
}

Controller:

public ActionResult Edit(int id)
{
    var model = new ArtistViewModel();
    model.artist = db.Artists.Find(id);
    
    if (model.artist.ArtistTags.Any())
    {
        model.PossibleTags = GetPossibleTags((from p in model.artist.ArtistTags select p.TagId).ToArray());
    }
    else
    {
        model.PossibleTags = GetPossibleTags(null);
    }

    return View(model);
}

private MultiSelectList GetPossibleTags(int[] selectedValues)
{
    return new MultiSelectList(db.Tags.OrderBy(o => o.Name).ToList(), "TagId", "Name", selectedValues);
}

View:

@Html.ListBoxFor(m => m.SelectedTags, Model.PossibleTags)

This example uses a View Model, but you should be able to figure out how to dump in in your View Bag, if so desired.  I think it would be easier if you used a View Model as this example uses.

[RESOLVED]Set the condition for two Dropdownlists using viewbag

Hi am new to mvc………..am using two dropdowns ( one is for minimum salary and the other is max salary) getting data from the controller using viewbag…….but i need to set the condition min salary should be less than max salary  for two drop downs………..can
anyone help me to solve it……..

THIS IS MY VIEW

 <dt>Annual salary</dt>
                                                    <dd> <%= Html.DropDownListFor(model => model.AnnualSalary.MinimumLakhs, new SelectList(ViewBag.Annualsalarylakhs1),"Lakhs",new {style="display:inline; width:90px;",@id="txtMinimumLakhs",@class="mid-size mr10",@placeholder="Laks"})%>
                                                        <%= Html.DropDownListFor(model => model.AnnualSalary.MinimumThousands, new SelectList(ViewBag.AnnualSalaryThousands1),"Thousands",new {style="width:90px;",@id="txtMinimumThousands",@class="mid-size",@placeholder="Thousands"})%></dd>
                                                    <dt>&nbsp;</dt>
                                                    <dt>To</dt>
                                                    <dt>&nbsp;</dt>
                                                    <dd><%= Html.DropDownListFor(model => model.AnnualSalary.MaximumLakhs, new SelectList(ViewBag.Annualsalarylakhs1),"Lakhs",new {style="display:inline; width:90px;",@id="txtMaximumLakhs",@placeholder="Laks",@class="mid-size mr10"})%>
                                                        <%= Html.DropDownListFor(model => model.AnnualSalary.MaximumThousands, new SelectList(ViewBag.AnnualSalaryThousands1),"Thousands",new {style="display:inline; width:90px;",@id="txtMaximumThousands",@placeholder="Thousands",@class="mid-size"})%></dd>
                                                    </dl>

Thanks in advance………

I have 3 suggestions that you could try

1) on-select-change, check if the minimum value is less than the maximum value.  If false, disable the Submit button to prevent posting and display alert to correct the values.

2) on-form-submit, check if the minimum value is less than the maximum value.  If false, prevent submission and display alert to correct values.

3) Check values at the  controller level, and if false, return a ModelStateError message back to view (I would not let your post get to controller though)

I would personally use #2 as it only requires checking at submission time, and doesn’t send any data to the controller if your validation fails

$("form").submit(function( event ) {
  if ($("#MinimumLakhs").val() > $("#MaximumLakhs").val()) {
alert("Minimum Lakhs must be less than maximum Lakhs");
event.preventDefault();
}

// do the same for "Thousands" if necessary });

When you submit your form, this event handler gets triggered.  It will then check your minimum Lakh value against the maximum value.  If it is false (greater than the maximum), it will alert the user to correct it.  The "preventDefault" method cancels the
submit event, preventing the form from being passed to controller.

Thank  u JohnLocke

 

Thank u johnLocke but i need the condition as 

When i select the a value in the dropdown  minlakhs then the values in the  maxlakhs drop down should start the range from what i selected the minlakhs dropdown …….

For example when i select minlakhs dropdown value as 4lakhs the values in the max lakhs drop down should start the range from 4lakhs……

How can i do this using viewbag……..

Please help me anyone……..

Thanks in advance………..

[RESOLVED]how to get selected text from dropdown in mvc5?

hi,

I am new to MVC.

I appended data to dropdownlist but i cant to get the selected item from dropdownlist( I did not used models i fetch the data using json in controller)

could any one guide me

how to to get selected (text/value) from dropdown in form post in mvc5

my code is:

HomeController:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace postbackevents.Controllers
{
    public class HomeController : Controller
    {
        string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        List<SelectListItem> Colleges = new List<SelectListItem>();
        List<SelectListItem> subjects = new List<SelectListItem>();
        List<SelectListItem> students = new List<SelectListItem>();
      
        //
        // GET: /Home/
       
        public ActionResult Index()
        {
            ViewBag.var1 = getColleges();
            ViewBag.var2 = subjects;
            ViewBag.var3 = students;
            return View();
        }
       

        private SelectList getColleges()
        {
            using(SqlConnection con=new SqlConnection(constr) )
            {
                try
                {
                    con.Open();
                    SqlDataReader dr = null;
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = "select Id,name from College";
                    cmd.Connection = con;
                    dr = cmd.ExecuteReader();
                    while(dr.Read())
                    {
                        Colleges.Add(new SelectListItem { Text = dr["name"].ToString(), Value = dr["Id"].ToString() });
                    }
                }
                catch(Exception ex)
                {
                    string msg = ex.Message;
                }
                return new SelectList(Colleges, "Value", "Text", "Id");
            }
        }
        public JsonResult getSubjects(int id)
        {

            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("select * from subjects where CollegeId =" + id + " ", conn);
                myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {

                    subjects.Add(new SelectListItem { Text = myReader["subname"].ToString(), Value = myReader["id"].ToString() });
                }
            }
            return Json(subjects, JsonRequestBehavior.AllowGet);

        }

        public JsonResult getStudents(int id)
        {

            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("select * from Students where SubId =" + id + " ", conn);
                myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {

                    students.Add(new SelectListItem { Text = myReader["StudentName"].ToString(), Value = myReader["Id"].ToString() });
                }
            }
            return Json(students, JsonRequestBehavior.AllowGet);

        }
	}
}

index.cshtml file:

@{
    ViewBag.Title = "Index";
}

<script src="../../Scripts/jquery-2.1.1.min.js" type="text/javascript"></script>
<h2>Index</h2>
Colleges @Html.DropDownList("var1","Select College")
Subjects          @Html.DropDownList("var2", "Choose")
Student          @Html.DropDownList("var3", "Choose")

<script type="text/javascript">
    $(function () {

        $("#var1").change(function () {
            var name = $("#var1 :selected").val();
            var url = 'Home/getSubjects';
            var data1 = { "id": name };
            $.post(url, data1, function (data) {
                var items = [];
                items.push("<option value=" + 0 + ">" + "Choose Subject" + "</option>");
                for (var i = 0; i < data.length; i++) {

                    items.push("<option value=" + data[i].Value + ">" + data[i].Text + "</option>");
                }
                $("#var2").html(items.join(' '));
                $("#var3").empty();
                $("#var3").append("<option>choose</option>");

            })
        });

        $("#var2").change(function () {
            var name = $("#var2 :selected").val();
            var url = 'Home/getStudents';
            var data1 = { "id": name };
            $.post(url, data1, function (data) {
                var items = [];
                items.push("<option value=" + 0 + ">" + "Choose team" + "</option>");
                for (var i = 0; i < data.length; i++) {

                    items.push("<option value=" + data[i].Value + ">" + data[i].Text + "</option>");
                }
                $("#var3").html(items.join(' '));


            })
        });
    });

        </script>
<form>
    <input type="submit" value="submit"  />
</form>

now i want when i click submit button

i want to show the output like

College=selected college Name

course=selected course name

student=selected student name

Thanks,

Murali.

you actually already have parts of that code.

$('#mysubmitbutton').click(function(e){
e.preventDefault(); var first = $("#var1 :selected").val(); var second = $("#var2 :selected").val(); var third = $("#var3 :selected").val(); // add your ajax post and give a json like { student : first, something : second, another : third } });

hope this helps a little

murali krishna14

now i want when i click submit button

i want to show the output like

College=selected college Name

course=selected course name

student=selected student name

Do you want to display this on the same view, or on the next view after you submit your form?

To simply display the selected item’s text, use:

// show school
$("#var1").text();

// show subject
$("#var2").text();

// show student
$("#var3").text();

Thanks sp00k,

I am a begineer

could you please post the code for this

 // add your ajax post and give a json like { student : first, something : second, another : third }

Hi John,

I want to return back those values to controller(action method)

based on those values i need to perform some calculations.

place the dropdowns and submit button on same form

@using(@Html.BeginForm("actionname","ControllerName",FormMethod.Post))
{
Colleges @Html.DropDownList("var1","Select College")
Subjects          @Html.DropDownList("var2", "Choose")
Student          @Html.DropDownList("var3", "Choose")

    <input type="submit" value="submit"  />
</form>
}

and write the action to post the values

[HttpPost]
public ActionResult SaveCylDetail(string var1,string var2,string var3)
{

}

Hi Murali,

First, if you can’t get the data in the action, please modify the code like this:

var data1 =JSON.stringify({ "id": name });

Secondly, to display the selected data, please refer to this code below:

$('#mysubmitbutton').click(function(e){
    e.preventDefault();
    var first = $("#var1 :selected").val();
    var second = $("#var2 :selected").val();
    var third = $("#var3 :selected").val();
    var result="";
    result=result+"College="+first+"n";
   result=result+"course="+second +"n";
result=result+"student="+third +"n";
alert(result);
   $("#targetDiv").val(result);
  });

Best Regards

Starain

murali krishna14

could you please post the code for this

here’s a sample post

        $.post(
            '@Url.Action("Edit", "PriceList")',
            { Id: id, ProductName: productName, Price: price, Category: category, __RequestVerificationToken: verificationtoken },
            function (product) {
               $('#productName').val('product.Name') 
            }, "json");

you can also make an ajax post like 

var myId = $('productId').val();
var data = "{ id : " + myId + " }";
$.ajax({
  type: "POST",
  url: @Url.Action("Edit", "PriceList"),
  data: data,
  success: function (e){
// e is the returned model or int or whatever you want to return
 },
  dataType: "json"
});

[RESOLVED]MVC – adding dynamic controls to each row in list

I have a dynamically created table with employee data (name/emp number/start date/title). We’re trying to keep track of the percent of an employee’s job doing certain duties.

What I need (for each employee) is to add a dropdown list with a list of duties, and then add a a textbox for percentage of time (don’t worry about percentage), but I need 4 of each per employee, named with some relevance to each employee

Like:

Emp Name-Emp Number – DropDownList – TextBox                                       

                                            DropDownList – TextBox                                       

                                            DropDownList – TextBox                                       

                                           DropDownList – TextBox

Each Dropdownlist will have the same items in it, and the end user will select from the DDL, and enter the number in the textbox.

I’ve tried this:

 for (int lines = 1; lines < 5; lines++)
    {
<tr>
    <td colspan="5">&nbsp;</td>
    <td class="altText">radio buttons</td>
    <td class="altText">ddlActivity + @item.empNumber + @lines.ToString()</td>
    <td class="altText">DropDown</td>
    <td class="altText">FTE Textbox</td>
    <td class="altText">Total FTETTextbox</td>
</tr>
    } 

But the output is more like the formula and not what I need: ddlActivity + (empNumber is correct) + 1 with the plus shines showing.

How can I create name these dynamic controls (and populate the dropdownlists) so that they’re tied to that particular employee?

elmoWatson

How can I create name these dynamic controls (and populate the dropdownlists) so that they’re tied to that particular employee?

Put the names as in the property – see http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

Also, it maybe worth to study MVVM in javascript http://msprogrammer.serviciipeweb.ro/2014/01/05/javascript-mvvm-and-asp-net-mvc/

My IQ Is not high enough to figure out jQuery and JSON in MVC Entity Framework

Drop down 1, has 5 choices. This doesn’t matter for this thread.
On .change of this dropdown I want to fire JSON that calls controller function
that returns data from database for the 2nd pulldown.
I already have a ton of harcoded pulldown examples. They all are hardcoded values like State/City, Country/Region
My needs are for dynamic data filled 2nd pulldown: (SELECT rows from DWS_BactiBucket WHERE Type=’R’ AND PWS=’99999′ AND IsTOTColiform = "1")
The only where criteria that is dynamic is the PWS . That is what i am sending it depending on what was entered.

Here is the second pulldown on Add view that should get filled at runtime using jQuery/Json

@Html.DropDownListFor(model => model.OrigSampID, new SelectList(Model.OrigSampID,"OrigSampID","SampDate"))

Here is the jQuery code at bottom of Add View.

//Hook onto the SampType list's onchange event 
$("#SampType").change(function() {

$.getJSON('Home/GetOriginalIDs', {thisPWS: $("#PWS").val() }, function (data) { 
//Clear the Model list 
$("#OrigSampID").empty(); 
//Foreach Model in the list, add a model option from the data returned 
$.each(data, function(index, optionData) { 
$("OrigSampID").append("<option value=" + optionData.OrigSampID + ">" + optionData.SampDate + "</option>"); 
});
}); 
}).change();

Here is the function in the HomeController that should get called and it hits the database with a query using the parameter supplied:

        public JsonResult GetOriginalIDs(string thisPWS)
        {
            
            JsonResult result = new JsonResult();

            var positives = (from c in _db.DWS_BactiBucket.OrderByDescending(x => x.SampDate)
                       where c.PWS == thisPWS && c.SampType == "R" && c.IsTOTPresent == "1"
                       select c).Take(6);

            result.Data = positives.ToList();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
          

        } 

So far all I get is this error:

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: items

and it points to the 2nd pulldown:

           @Html.DropDownListFor(model => model.OrigSampID, new SelectList(Model.OrigSampID,"OrigSampID","SampDate"))

I know the LINQ query works to populate a pulldown on form load. 
I just need to catch if 1st pulldown changes. The value doesn’t matter for now.
Once picked from 1st pulldown, the PWS id is sent to the controller function to 
ask the database for rows that are relevant. 

who is 

Challenged

Model.OrigSampID

from 

Challenged

new SelectList(Model.OrigSampID,"OrigSampID","SampDate"))

?

[RESOLVED]how to add,edit,delete records using gridview in mvc .I want to use dropdown list ,radio button inside grid

Hi

i want to  add,edit,delete records using gridview in mvc .I want to use dropdown list ,radio button inside grid.

Also I want to use dropdownlist  to fetch data from database in cshtml page.

Please help me.

Thanks and Regards

chandran

You can’t use gridview in asp.net MVC, which is a server control avail in ASP.Net WebForm applications.

In MVC, you can go with the "webgrid" as the previous poster said.

Hi rchandran.nr,

Thanks for your post.

According to your description,

rchandran.nr

how to add,edit,delete records using gridview in mvc .I want to use dropdown list ,radio button i

As community member mentioned,there’s no server control(Gridview) in mvc,you can use webgrid,please refer to this:

Inline Editing With the WebGrid in ASP.NET MVC 4

And you can check this:http://msprogrammer.serviciipeweb.ro/2011/12/05/jquery-ajax-request-and-mvcdetailed/

Hope this can be helpful.

Best Regards,

Eileen

[RESOLVED]Create a gridview like structure in MVC 5 Razor.

Hello All,

I am new to MVC Concept , so the question may be a dumb one , but i wanted to know , my requirement goes like this:

I have a table with come columns and according to the column values i need to show textbox or dropdownlist (like we used to do in gridivew template field with some conditions.) , since this is mvc and i suppose there is nothing called as gridview as all
the controls are html so m blind at this point , where shall i start ? Morover i need to edit and delete rows also. 

Any tutorials on how to handle these kind of situations ?

A few suggestions are here

http://stackoverflow.com/questions/177275/grid-controls-for-asp-net-mvc

A quick glance show that most are javascript based, if you want something that works without js then you’ll probably need to do your own.  Rather than using an off-the-shelf component you could use this as an opportunity to learn http and mvc and how they
work, as it will see you in good stead for the future.  You don’t want to be one of those developers that has to constantly come here to ask people to do their work for them.

[RESOLVED]How to fetch the value from dropdownlist in MVC?

In my one of the view I add a dropdown and I bind this drop down with my database like this..

public ActionResult PostMarks()
        {
            JoinMod std = new JoinMod();
            std.Drp_bind = (from nm in db.TbStudent
                            select new SelectListItem
                            {
                                Text = nm.StudentName,
                                Value = SqlFunctions.StringConvert((double)nm.StudentId).Trim()
                            }).ToList<SelectListItem>();
       

            return View(std);

        }

Here is the dropdownlist in my view

<p>StudentName</p>
    @Html.DropDownList("StudentName",Model.Drp_bind,"Select")


And on Post I am trying to save the data into the database like this 

 [HttpPost]
        public ActionResult PostMarks(Marks marks)
        {
           
            db.TbMarks.Add(marks);
            db.SaveChanges();
            return RedirectToAction("ShowAllMarks");



        }

Now when I check my database after save data in database the Id save in the database is zero from the dropdownlist. Please experts help me to solve this issue

Azad Chouhan

@Html.DropDownList("StudentName",Model.Drp_bind,"Select")

since you name dropdown with StudentName, Does your Marks have the property StudentName? 

Azad Chouhan

PostMarks(Marks marks)

The marks is populated by MVC model binding. This binding happens by naming convention. Please take a look at this article to understand how this works.

Understanding ASP.NET MVC Model Binding

[RESOLVED]MVC Complex Model Binding

I have two C# POCO class 

public partial class Hotel
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Hotel_Rate Rate { get; set; }

}



public partial class Hotel_Rate
{
public Hotel_Rate()
{
this.Hotel = new HashSet<Hotel>();
}

public int Id { get; set; }
public string Rate { get; set; }
public string Description { get; set; }

public virtual ICollection<Hotel> Hotel { get; set; }
}

I have a viewBag for To Populate dropdown list from Hotel_Rate Class as below

 ViewBag.Hotel_Rate = new SelectList(db.Hotel_Rate, "Id", "Rate");

and in Create View For Hotel Model View Bag Is Used as below 

 @Html.DropDownListFor(m => m.Rate.Id, (SelectList)ViewBag.Hotel_Rate)

and Hotel controller [Create] methode as below

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Rate")] Hotel hotel)
        {
            if (ModelState.IsValid)
            {
                
                db.Hotels.Add(hotel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.Hotel_Rate = new SelectList(db.Hotel_Rate, "Id", "Rate", hotel.Id);
            return View(hotel);
        }

,
but i get the System.Data.Entity.Validation.DbEntityValidationException Error , i entered ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors in watch windows and drilled down to error 

"The Rate field is required."

"The Description field is required."

i change to 

 @Html.DropDownListFor(m => m.Rate.Rate, (SelectList)ViewBag.Hotel_Rate)

and this time The Describtion field is required.

i drilled to Hotel.Rate object in debugging mode , rate property is populated with Hotel_Rate object i drilled down one step more , the id of hotel_rate object is 0 and the rate is 1 (id of rate from  database )

i am really frustrated how difficult  it is to handle simple case in asp.net mvc .

i don’t want to use custom model binder . default asp.net mvc model binder should  be able to handle this .
 

how can i handle this without complex code , just simple model binding ? 

i dont think viewModel is Good option , because writing viewmodel class just for simple scenario is really funny , 

In my project, I present a dropdown list like below, at same time, you may check if the SelectList object is correctly built.

 public ActionResult Create()
        {
            var categories = from category in db.Categories
                             select category;
            var slist = new List<SelectListItem>();
            foreach (var category in categories)
            {
                slist.Add(new SelectListItem() { Value = category.Description, Text = category.Description, Selected = true });
            }
            ViewData["categories"] = slist;
            return View();
        }

 @Html.DropDownListFor(model => model.CategoryName, (IEnumerable<SelectListItem>)ViewData["categories"])