简体   繁体   English

尝试从部分视图调用 ajax 后更改文本框

[英]Trying to change a textbox after an ajax call from a partial view

Im trying to change a "name" textbox color to (blue if it is male, and pink if it is female) after changing a "gender" dropdown in a partial view.在部分视图中更改“性别”下拉列表后,我试图将“名称”文本框颜色更改为(如果是男性,则为蓝色,如果是女性,则为粉红色)。

Index View:索引视图:

@{
    ViewData["Title"] = "Home Page";
    var gender = ViewBag.Gender; //breakpoint
}
 @if (gender == "Male") 
{
    <div id="name">
        <label asp-for="Name">Name</label>
        <input id="nametextbox" type="text" asp-for="Name" style="background-color: lightblue" />
    </div>
}
else if (gender == "Female")
{
    <div id="name">
        <label asp-for="Name">Name</label>
        <input id="nametextbox" type="text" asp-for="Name" style="background-color: lightpink" />
    </div>
}
else
{
    <div id="name">
        <label asp-for="Name">Name</label>
        <input id="nametextbox" type="text" asp-for="Name" style="background-color: white" />
    </div>
}
<div id="gender">
    <partial name="_GenderDropdown" model="Model" />
</div>

Partial View:局部视图:

<label>Gender</label>
<select id="genderstring">
    <option value="">Select Gender</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        //ajax for posting gender to controller

        $('#genderstring').on('change', function () {
            $.ajax({
                url: '@Url.Action("Index", "Home")',
                type: 'GET',
                data: { gender: $("#genderstring").val() },
                success: function () {
                
                },
                error: function () {
                
                }
            });
        });

    });

</script>

Controller: Controller:

public IActionResult Index(string gender)
    {

        if(gender == null)
        {
            return View(new User { Name = "", Gender = "" });
        }
        else
        {
            ViewBag.Gender = gender;
            return View("Index"); //breakpoint
        }
    }

With this 2 breakpoints i can see that the data is passing but after I change the gender it gets to the view with the gender in the viewbag but the rest of the page doesen't run.有了这两个断点,我可以看到数据正在传递,但是在我更改性别后,它会以视图袋中的性别进入视图,但页面的 rest 没有运行。

When you use ajax,it would not reload your page after backend code finishing by default.More detailed explanation and solution you could check as follow:当您使用 ajax 时,默认不会在后端代码完成后重新加载您的页面。更详细的解释和解决方案您可以查看以下内容:

The first way第一种方式

You could use .html() method to render the backend result to html after ajax success:在 ajax 成功后,您可以使用.html()方法将后端结果呈现给 html:

1.View(Be sure add a div to contain the whole html ): 1.查看(请务必添加一个 div 以包含整个 html ):

<div id="result">    //add the div......
    @if (gender == "Male")
    {
        <div id="name">
            <label asp-for="Name">Name</label>
            <input id="nametextbox" type="text" asp-for="Name" style="background-color: lightblue" />
        </div>
    }
    else if (gender == "Female")
    {
        <div id="name">
            <label asp-for="Name">Name</label>
            <input id="nametextbox" type="text" asp-for="Name" style="background-color: lightpink" />
        </div>
    }
    else
    {
        <div id="name">
            <label asp-for="Name">Name</label>
            <input id="nametextbox" type="text" asp-for="Name" style="background-color: white" />
        </div>
    }
    <div id="gender">
        <partial name="_GenderDropdown" model="Model" />
    </div>
</div>

2.Js in partial view: 2.局部视图中的Js:

<script>
    $(document).ready(function () {    
        $('#genderstring').on('change', function () {
            $.ajax({
                url: '@Url.Action("Index", "Home")',
                type: 'GET',
                data: { gender: $("#genderstring").val() },
                success: function (res) {
                    $("#result").html(res);   //add this...
                },
                error: function () {

                }
            });
        });

    });

</script>

3.Controller: 3.Controller:

You need return PartialView instead of returning View,because if you return view it will generate the layout(eg the nav bar) again (you could have a try by yourself).您需要返回 PartialView 而不是返回 View,因为如果您返回 View,它将再次生成布局(例如导航栏)(您可以自己尝试)。

[HttpGet]
public IActionResult Index(string gender)
{

    if (gender == null)
    {
        return View(new User { Name = "", Gender = "" });
    }
    else
    {
        ViewBag.Gender = gender;
        return PartialView("Index"); //change here...
    }
}

Result:结果:

在此处输入图像描述


The second way第二种方式

You could avoid using ajax,just use window.location.href to reload the page(The view and controller are the same as yours, do not change like the first way ):您可以避免使用 ajax,只需使用window.location.href重新加载页面(视图和 controller 与您的相同,不要第一种方式一样更改):

<script>
    $(document).ready(function () {    
        $('#genderstring').on('change', function () {
            window.location.href = "/Home/Index?gender=" + $("#genderstring").val();               
        });

    });  
</script>

Result:结果:

在此处输入图像描述

Note:笔记:

If you want to maintain the select list selected item ,you may choose the first way,and modify your js like below:如果你想维护select 列表中的选中项,你可以选择第一种方式,修改你的js如下:

<script>
    $(document).ready(function () {
        //ajax for posting gender to controller

        $('#genderstring').on('change', function () {
            var selected_item = $("#genderstring").val(); //add this ....

            $.ajax({
                url: '@Url.Action("Index", "Home")',
                type: 'GET',
                data: { gender: selected_item },
                success: function (res) {
                    $("#result").html(res);  
                    $("#genderstring").val(selected_item);   //add this....
                },
                error: function () {
                }
            });
        });

    });

</script>

Result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM