Controller for partial view in asp.NET 5 MVC

Iwould like to set a partial View in a form. The problem is that I would like this partial View to be controlled by a controller.

Here is the code of the form :

<select asp-for="Categorie" id="categorie">
    <partial name="BudgetSearch" />
</select>

Here is the code of the controller :

public IActionResult BudgetSearch()
    {
        var bdd = new ComptesBudgetViewModel();

        return PartialView(bdd);
    }

Here is the code of the partia View :

@model Comptes.core.data.DataLayer.HomeDataLayer.ComptesBudgetViewModel

<option value="" selected>Choisir</option>
@foreach (var budget in Model.Budget)
{
    <option value="@budget.Categorie">@budget.Categorie</option>
}

Can someone help me ?

3 answers

  • answered 2021-02-19 12:51 meysam asadi

    enter Your controller Name into this code: load('/ControllerName/BudgetSearch')

    full code

    <select asp-for="Categorie" id="categorie">
         
    </select>
    
    
    @section scripts{
        <script>
           $('#categorie').load('/ControllerName/BudgetSearch');
        </script>
    }
    

    And Other Way

    public IActionResult MYAction()
    {
       var bdd = new ComptesBudgetViewModel();
       return View(bdd);
    }
    

    Your View

    <select asp-for="Categorie" id="categorie">
        @Html.Partial("BudgetSearch")
    </select>
    

  • answered 2021-02-19 12:54 firoz khan

    /*to load the partial view in main view on click of button*/
    $("#btnId").on("click", function () {                          //on button click function using its id
        var suppName = document.getElementById("searchTxt").value;     //to get value of textbox using its id
    
       /*.get is used to get the partial view having 3 parameter one is url to the partial view
        * 2nd is variable value which you want to pass to controller and same name should be used in controller here in { name: name} 1st name is name should include in controller and 2nd one is variable name
        * 3rd is function to get data in our view #divContaiPopup is the div or place where partial view will be loaded*/
        $.get('@Url.Action("methodNameinController")', { name: name}, function (data) {
            $("#divContaiPopup").html(data);
      });
    
    });
    
    
    
    public ActionResult methodNmae(string name)
        {
            var data= new modelClass()
            { 
                modelclass = db.modelname.Where(a=> a.dbTableName.fieldName.Contains(name)).ToList(),
                
            };
            return View("PartialView", data);
        }
    

  • answered 2021-02-19 20:25 mxmissile

    Use @Html.Action("MyController","BudgetSearch"), this will call the Controller Action and return the related view inline, some claim its not pure MVC, but I have used it with success before.