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

Viewed 55

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" class="btn btn-pink btn-sm">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 .

2 Answers

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
    }
 // Summary:
        //     Initialize a new instance of Microsoft.AspNetCore.Mvc.Rendering.SelectList.
        //
        // Parameters:
        //   items:
        //     The items.
        //
        //   dataValueField:
        //     The data value field.
        //
        //   dataTextField:
        //     The data text field.
        //
        //   selectedValue:
        //     The selected value.
        public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)
        {
            throw null;
        }

You can find SelectLIst class have an overloads that can pass selectedvalue, So you just need to change the code in your post method like:

[HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult MyPostAction(RecommendModel recommendModel)
    {
        
        //posting data and redirecting to same view 

        List<RecommendModel> dropdownlist = new List<RecommendModel>();
        dropdownlist = gateway.SelectDomainByCompanyID(CompanyID);
        ViewBag.ddl2= new SelectList(dropdownlist , "ID", "Name",recommendModel.ID);
        
        //Here just return `View` instead of `RedirectToAction`, otherwise you will get in get method agagin.
        return View("DropdownDisplay");
        
    }

Demo:

enter image description here

Related