Sanjay Maharjan
Sanjay Maharjan

Reputation: 671

Passing value from EditorFor to controller

This is my view where education is the list in the model.

 @using chpayroll.Models.CustInformations
 @model CustInfoExtract

 @Html.HiddenFor(x => x.flag, new { @id = "flag" })
      @Html.HiddenFor(x => x.StaffId)
        <table style=" width:730px">    
            <tr>
                <th>Country</th>
                <th>Board</th>
                <th>Level</th>
                <th>PassedYear</th>
                <th>Division</th>
            </tr>     
            <tr> 
               @Html.EditorFor(x => x.education)
            </tr>
            <tr>
               <td><input type="submit" value="Add Another" id="addedu"/> </td> 
            </tr>
        </table> 

I have editor template as below

@using staffInfoDetails.Models
@model staffInfo.education

@Html.HiddenFor(x=>x.staffId)

<tr>
    <td >@Html.DropDownListFor(x => x.country, Model.countryList, "--select--", new { @id="country"})</td>
    <td>@Html.TextBoxFor(x => x.board, new { @id="board"})</td>
    <td>@Html.TextBoxFor(x => x.level, new { @id="level"})</td>
    <td>@Html.TextBoxFor(x => x.passedYr, new { @id="passedYr"})</td>
    <td>@Html.DropDownListFor(x => x.passedDiv, Model.passedDivList, "--select--", new { @id="division"})</td>
</tr>

I am trying to pass model from controller to view and back from view to controller. While I was passing model to view, the education list passed, but, when i tried to pass model from view to controller, everything else passed except for the education list. How can I solve this problem ?

Upvotes: 2

Views: 1394

Answers (1)

David Spence
David Spence

Reputation: 8079

Only the selected value from the drop down list will be posted back so you'll need to re-populate your drop down list if validation fails (ie. if the View has to be re-displayed).

Your POST action might look something along the lines of the following:

[HttpPost]
public ActionResult Home(CustInformations viewModel)
{
    if (!ModelState.IsValid)
    {
        // Re-populate drop-down list and redisplay form
        viewModel.DropdownListOptions = _repository.getEductionList();
        return View(viewModel);
    }

    // Validation passed
    // Save, update, etc and redirect to new page
}

Upvotes: 1

Related Questions