質問

Im working with MVC 4 (razor).

I am using dropdownlist instead of dropdownlistFor because the dropdownlist can display selected value by retrieving data from database. So I need to know how to pass value by selecting a value from dropdownlist to Action parameter (Edit) without using dropdownlistfor model. Is there a way to solve it? I see VmCarList of ViewModel is null.

ViewModels

public IEnumerable<Cars> VmCarList { get; set; }
public CarData VmCarData { get; set; }

Controller

[HttpGet]
public ActionResult Edit(int id)
    {


        _viewModels.VmCarList = Repository.LoadAllCarNames();

        string selectedCar = (from car in _viewModels.CarList
                           where car.carId == id
                           select car.Name).First();

        ViewBag.CarNames = new SelectList(_viewModels.CarList, "CarName", "CarName", selectedCar);

        return View(_viewModels);
    }

View

    @model CarProgram.Models.ViewModels

    @Html.DropDownList("CarList", (SelectList)ViewBag.CarNames)

Controller

    [HttpPost]
    public ActionResult Edit(int id, ViewModels data)
    {
        try
        {
            if (ModelState.IsValid)
            {
                var car = new CarData();
                UpdateModel(car);

                bool result = Repository.UpdateCar(car);
            }

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
役に立ちましたか?

解決

If you use @Html.DropDownList("CarList", (SelectList)ViewBag.CarNames), you should add CarList to action as parameter. Or if you want to receive car value from model, you should use DropDownListFor:

@Html.DropDownListFor(model => model.VmCarData, ViewBag.CarNames as IEnumerable<SelectListItem>, "-Select Car-", new { @id = "carDDL" })
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top