How to rebind dropdown after RedirectToAction("Index") using ViewBag in ASP.NET Core MVC?

huangapple go评论76阅读模式
英文:

How to rebind dropdown after RedirectToAction("Index") using ViewBag in ASP.NET Core MVC?

问题

I understand that you want a translation of the provided code, excluding the code parts. Here's the translation:

在使用 ViewBag 绑定下拉列表数据到视图时遇到问题。成功获取数据并将其放入 ViewBag 中,但是在视图上没有替换下拉列表的值。

以下是绑定到 ViewBag 的 Index 页面:

Index.cshtml

<div class="col-md-6">
    <label for="option1">System Role</label>
    <select id="rolelist" name="rolelist" class="form-control">
        <option value="">Select System Role</option>
        @foreach (var role in ViewBag.RoleList)
        {
            <option value="@role.roleId">@role.roleName</option>
        }
    </select>
</div>

而这是控制器页面,从数据库中获取值并在单选按钮点击时分配给 ViewBag,具有不同的下拉列表值并重定向到 Index.cshtml 页面:

public async Task<IActionResult> Index()
{
    if (TempData["RoleCode"] != null)
    {
        string RoleCode = TempData["RoleCode"].ToString();

        List<RoleModel> roleList = JsonConvert.DeserializeObject<List<RoleModel>>(await _commonService.GetSystemRole(TempData["RoleCode"].ToString())).ToList();
        ViewBag.RoleList = roleList;
    }
    else
    {
        List<object> roleList = JsonConvert.DeserializeObject<List<object>>(await _commonService.GetSystemRole("MAAD"));
        ViewBag.RoleList = roleList;
    }

    return View();
}

[HttpPost]
public async Task<IActionResult> HandleRadioButton(string access)
{
    string RoleCode = string.Empty;

    if (access == "MasterAccess")
    {
        RoleCode = "MAAD";
    }
    else if (access == "StudyAccess")
    {
        RoleCode = "";
    }

    TempData["RoleCode"] = RoleCode;

    return RedirectToAction("Index");
}

If you have any specific questions or need further assistance, please let me know.

英文:

Getting issue during binding dropdown data to view using ViewBag. Getting Data properly and putting to the viewbag but it's not replacing the dropdown value on view.

Below is the Index page that binding with dropdown with viewbag-

Index.cshtml:

&lt;div class=&quot;col-md-6&quot;&gt;
    &lt;label for=&quot;option1&quot;&gt;System Role&lt;/label&gt;
    &lt;select id=&quot;rolelist&quot; name=&quot;rolelist&quot; class=&quot;form-control&quot;&gt;
        &lt;option value=&quot;&quot;&gt;Select System Role&lt;/option&gt;
        @foreach (var role in ViewBag.RoleList)
        {
            &lt;option value=&quot;@role.roleId&quot;&gt;@role.roleName&lt;/option&gt;
        }
    &lt;/select&gt;
&lt;/div&gt;

And, this is the controller page where getting value from database and assigned to to viewbag on radio button click with different dropdown values and redirecting to the Index.cshtml page:

public async Task&lt;IActionResult&gt; Index()
{
        if (TempData[&quot;RoleCode&quot;] != null)
        {
            string RoleCode = TempData[&quot;RoleCode&quot;].ToString();

            List&lt;RoleModel&gt; roleList = JsonConvert.DeserializeObject&lt;List&lt;RoleModel&gt;&gt;(await _commonService.GetSystemRole(TempData[&quot;RoleCode&quot;].ToString())).ToList();
            ViewBag.RoleList = roleList;
        }
        else
        {
            List&lt;object&gt; roleList = JsonConvert.DeserializeObject&lt;List&lt;object&gt;&gt;(await _commonService.GetSystemRole(&quot;MAAD&quot;));
            ViewBag.RoleList = roleList;
        }

        return View();
}

[HttpPost]
public async Task&lt;IActionResult&gt; HandleRadioButton(string access)
{
        string RoleCode = string.Empty;

        if (access == &quot;MasterAccess&quot;)
        {
            RoleCode = &quot;MAAD&quot;;
        }
        else if (access == &quot;StudyAccess&quot;)
        {
            RoleCode = &quot;&quot;;
        }

        TempData[&quot;RoleCode&quot;] = RoleCode;

        return RedirectToAction(&quot;Index&quot;);
}

答案1

得分: 1

由于您正在尝试使用 ajax,您必须在 js/jquery 代码中重定向到目标 URL 或者自行更新 DOM。

基于您的设计的一个最小示例:

public class MyController : Controller
{
    // ... (您的其他代码)

    public IActionResult DropDown(string access)
    {
        TempData["access"] = access;
        return Ok();
    }
}

视图:

<div id="mydropdownpartial">
     <partial name="DropDown"></partial>
</div>
<div>
  <label>奇数</label>
    <input  type="radio" name="sel" value="odd" />
    <label>偶数</label>
    <input  type="radio" name="sel" value="even" />
</div>

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>    
    $(":radio").click(function () {
        var access = $(this).val()
        
        $.ajax({
            url: "DropDown?access=" + access,
            success: function(response) {
                // 在这里刷新您的页面
                window.location.href = "Index";
            }
        })
    })
</script>

部分视图:

<div class="col-md-6">
    <label for="option1">系统角色</label>
    <select id="rolelist" name="rolelist" class="form-control">
        <option value="">选择系统角色</option>
        @foreach (var role in (ViewBag.RoleList as List<Role>))
        {
            <option value="@role.roleId">@role.roleName</option>
        }
    </select>
</div>

如果您只想刷新下拉菜单,您可以尝试以下方法:

public class MyController : Controller
{
    // ... (您的其他代码)

    public IActionResult DropDown(string access)
    {
        if (access == "odd")
        {
            Roles = Roles.Where(x => x.roleId % 2 != 0).ToList();
        }
        else if (access == "even")
        {
            Roles = Roles.Where(x => x.roleId % 2 == 0).ToList();
        }

        ViewBag.RoleList = Roles;

        return PartialView();
    }
}

jQuery 代码:

$(":radio").click(function () {
        var access=$(this).val()
        console.log(access)
        $.ajax({
            url: "DropDown?access=" + access,
            success: function(response){
                $("#mydropdownpartial").html(response)
            }
        })
    })

您可以看到,单选按钮保留了选定的值。

英文:

Since you are trying with ajax,you have to redirect to target url or update dom youreslf in js/jquery codes

A minimal example based on your design:

public class MyController : Controller
    {

        private List&lt;Role&gt; Roles= Enumerable.Range(1, 5).Select(x =&gt; new Role
        {
            roleId = x,
            roleName=String.Format(&quot;RoleName{0}&quot;,x.ToString())
        }).ToList();
            
        public IActionResult Index()
        {
            var access = TempData[&quot;access&quot;]?.ToString()??&quot;&quot;;
            if (access == &quot;odd&quot;)
            {
                Roles = Roles.Where(x =&gt; x.roleId % 2 != 0).ToList();
            }
             if (access == &quot;even&quot;)
            {
                Roles = Roles.Where(x =&gt; x.roleId % 2 == 0).ToList();
            }
            ViewBag.RoleList=Roles;
            return View();
        }

        public IActionResult DropDown(string access)
        {
            TempData[&quot;access&quot;] = access;
            return Ok();
            
        }

View:

&lt;div id=&quot;mydropdownpartial&quot;&gt;
     &lt;partial name=&quot;DropDown&quot;&gt;&lt;/partial&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;lable&gt;Odd&lt;/lable&gt;
    &lt;input  type=&quot;radio&quot; name=&quot;sel&quot; value=&quot;odd&quot; /&gt;
    &lt;lable&gt;Even&lt;/lable&gt;
&lt;input  type=&quot;radio&quot; name=&quot;sel&quot; value=&quot;even&quot; /&gt;
&lt;/div&gt;

&lt;script src=&quot;~/lib/jquery/dist/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;    
    $(&quot;:radio&quot;).click(function () {
        var access=$(this).val()
        
        $.ajax({
            url: &quot;DropDown?access=&quot;+access,
            success:function(response){
                //refresh your page here
                window.location.href=&quot;Index&quot;
            }
        })
    })
&lt;/script&gt;

Partial:

&lt;div class=&quot;col-md-6&quot;&gt;
    &lt;label for=&quot;option1&quot;&gt;System Role&lt;/label&gt;
    &lt;select id=&quot;rolelist&quot; name=&quot;rolelist&quot; class=&quot;form-control&quot;&gt;
        &lt;option value=&quot;&quot;&gt;Select System Role&lt;/option&gt;
        @foreach (var role in (ViewBag.RoleList as List&lt;Role&gt;))
        {
            &lt;option value=&quot;@role.roleId&quot;&gt;@role.roleName&lt;/option&gt;
        }
    &lt;/select&gt;
&lt;/div&gt;

Result:
How to rebind dropdown after RedirectToAction("Index") using ViewBag in ASP.NET Core MVC?

If you just want to refresh your dropdown,you could try as below:

public class MyController : Controller
    {

        private List&lt;Role&gt; Roles= Enumerable.Range(1, 5).Select(x =&gt; new Role
        {
            roleId = x,
            roleName=String.Format(&quot;RoleName{0}&quot;,x.ToString())
        }).ToList();
            
        public IActionResult Index()
        {
            
            ViewBag.RoleList=Roles;
            return View();
        }

        public IActionResult DropDown(string access)
        {
            
            if (access == &quot;odd&quot;)
            {
                Roles = Roles.Where(x =&gt; x.roleId % 2 != 0).ToList();
            }
            else if (access == &quot;even&quot;)
            {
                Roles = Roles.Where(x =&gt; x.roleId % 2 == 0).ToList();
            }

            ViewBag.RoleList = Roles;


            return PartialView();
        }
    }

jquery codes:

$(&quot;:radio&quot;).click(function () {
        var access=$(this).val()
        console.log(access)
        $.ajax({
            url: &quot;DropDown?access=&quot;+access,
            success:function(response){
                $(&quot;#mydropdownpartial&quot;).html(response)
                
            }
        })
    })

Result:

How to rebind dropdown after RedirectToAction("Index") using ViewBag in ASP.NET Core MVC?
You could see that the radio button keeps the selected value

huangapple
  • 本文由 发表于 2023年7月13日 13:20:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76676159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定