Home > database >  How can i keep dropown selected values after HttpPost method in mvc?
How can i keep dropown selected values after HttpPost method in mvc?

Time:09-15

I'm loading dropdown value database.

My view DropdownDisplay.cshtml

@model RecommendModel                                           
<form asp-controller="Sample" asp-action="MyPostAction" method="post">
@if (ViewBag.ddl2 != null)
{
@Html.DropDownListFor(m => m.ID, ViewBag.ddl2 as SelectList, "Select value", new { @class = "form-control", @required = "required" })
 }
<button id="btnSubmit" >Submit</button>
   </form>

My Controller Recommendation.cs

[HttpGet]
    public ActionResult DropdownDisplay(string eID)
    {
        List<RecommendModel> dropdownlist = new List<RecommendModel>();
        dropdownlist = gateway.SelectDomainByCompanyID(CompanyID);
        ViewBag.ddl2= new SelectList(dropdownlist , "ID", "Name");  
        return View();
    }
    
    
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult MyPostAction(RecommendModel recommendModel)
    {
        
        //posting data and redirecting to same view 
        
        return RedirectToAction("DropdownDisplay", "Recommendation");
        
    }

How can keep Selected values after post method and redirected to same view. Also you can suggest another apporach .

CodePudding user response:

Pass your values using __doPostBack() function from javascript for that you need to pass 2 parameters in your __doPostBack function 1- EVENTTARGET (contain the control which is clicked) 2- EVENTARGUMENT (any value that you want to save)

so use it like this

__doPostBack("<%=document.getElementById('yourcontrolid.ClientId')%>","your parameters that you want to save");

but for __doPostBack to work you need a Script Manager in your html file so insert a script manager there and then set a OnClientClick="yourJavaScriptFunction();" on your dropdownlist control then set AutoPostBack to true when you select a value from dropdown so it can reload the page but while you do that yo have to initialize yourJavaScriptFunction() inside a script tag which contain your doPostBack function in short like this

i.e.

<asp:DropDownList runat="server" Id="dropdownlist1" ClientIdMode="static" OnClientClick="yourJavaScriptFunction();" OnClick="DropDownList_SelectedIndexChange" >

<script>


function yourJavaScriptFunction() {
__doPostBack("<%=document.getElementById('dropdownlist1.ClientId')%>","your parameters that you want to save");}

and for code on aspx.cs file create an event function that catch the postback

    public void DropDownList1_SelectedIndexChange(object sender, EventArgs e)
    {
    //yourcode
    }

CodePudding user response:

It will make easier if to apply some changes to the view data model.

Use the following view model:

public class ViewModel
{
    public IList<SelectListItem> SelectedCompanies { get; set; }
    public int? SelectedCompanyId { get; set; }
}

This structure of the view data model will provide an ability to keep the selected item, pass it to the controller and use it as selected when rendering the view the next time.

Preparing the data model in the controller and passing it to the strongly typed view:

[HttpGet]
public ActionResult DropDownDisplay(string eID)
{
    var dropdownlist = new List<RecommendModel>();
    dropdownlist = gateway.SelectDomainByCompanyID(CompanyID);
    //dropdownlist.Insert(0, new RecommendModel { ID = 0, Name = "Select value" });    

    var vm = new ViewModel()
    {
        SelectedCompanies = new SelectList(dropdownlist, "ID", "Name").ToList()    
    };
    //vm.SelectedCompanyId = 2; // Set default value if it's necessary
    return View(vm);
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult MyPostAction(ViewModel vm)
{
    if (ModelState.IsValid)
    {
        // Processing data ...
    }
    return View("DropDownDisplay", vm);
}

And in the view:

@model Models.ViewModel

<form asp-controller="Sample" asp-action="MyPostAction" method="post">
    <div asp-validation-summary="ModelOnly" ></div>
    @*
        This `for` loop is used to prepare a hidden context for the MVC binding to be used properly on the controller side.
        The `SelectedCompanies` values will be posted to controller and used when redirected to the
        view the next time.
        An another approach is to pass only the selected value and use it to prepare `SelectedCompanies` list
        in the same way as it created the first time.
    *@

    @for (int i = 0; i < Model.SelectedCompanies.Count(); i  )
    {
        @Html.Hidden("SelectedCompanies["   i   "].Text", Model.SelectedCompanies[i].Text)
        @Html.Hidden("SelectedCompanies["   i   "].Value", Model.SelectedCompanies[i].Value)
    }

    <div >
        @Html.DropDownListFor(model => model.SelectedCompanyId, Model.SelectedCompanies, "Select a value", new { @class = "form-control", @required = "required" })
    </div>
    <br>
    <input type="submit" value="Submit"  />
</form>

enter image description here

  • Related