2

I am writing MVC listing page which need to bundle with dropdownlist.
As I am very junior to ASP.net MVC, i don't know how to make dropdownlist to run correctly and make selected dynamically.

I have two model classes

public class CycleType
{
    public int CycleTypeID { get; set; }
    public string Type { get; set; }

    public List<CycleModel> CycleModels { get; set; }
}

-----------------------------------------------------------   

public class CycleModel
{
    public int CycleModelID { get; set; }
    public int CycleTypeID { get; set; }
    public string Model { get; set; }

    public virtual CycleType CycleType { get; set; }
}

Then one Controller class,

public class CycleModelController : Controller
{
UnitOfWork<CycleModel> unitOfWork = new UnitOfWork<CycleModel>();
UnitOfWork<CycleType> unitOfWork_cycleType = new UnitOfWork<CycleType>();

...

[HttpGet]
public ActionResult Edit(int CycleModelID)
{
    CycleModel cycleModel = unitOfWork.GenericTEntityRepository.GetByID(CycleModelID);
    ViewBag.CycleType = new SelectList(unitOfWork_cycleType.GenericTEntityRepository.Get(orderBy: CycleTypes => CycleTypes.OrderBy(CycleType => CycleType.Type)));
    return View(cycleModel);
}

...
}

Then One Razor file,

<div class="editor-field">
@*Html.DropDownList("CycleType")*@
@*Html.EditorFor(model => model.CycleTypeID)*@

@Html.DropDownListFor(model => model.CycleTypeID,
                                new SelectList(ViewBag.CycleType, "Type", "CycleTypeID"))
@Html.ValidationMessageFor(model => model.CycleTypeID)
</div>

When I run my program, I get error message

DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Type'.

1)How could I make correct this code ?
2)How could I make select item dynamically ?

Every suggestion will be really appreciated.

 

1 Answer 1

2

The ViewBag.CycleType is already a SelectList. Hence you can use that directly.

@Html.DropDownListFor(model => model.CycleTypeID, (SelectList)ViewBag.CycleType)

You can change the controller code as follows.

ViewBag.CycleType = new SelectList(
      unitOfWork_cycleType.GenericTEntityRepository.Get(
      orderBy: CycleTypes => CycleTypes.OrderBy(CycleType => CycleType.Type)), 
      "Type", "CycleTypeID");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.