select传值给后台、根据后台值选中

133 阅读1分钟

一、问题描述

  • 最近开发一个功能,后台逻辑已处理完毕,前端页面需要对应适配。由于是一个人负责维护这个项目,所以前端的活也得自己干。
  • 某个实体类新增、修改为同一个jsp页面,使用form表单向后端传递数据。其中有个select选择框,需要达到的效果为:新增的时候 显示默认值,修改的时候 显示从后端传过来的值。

二、代码实现

新增的时候能显示设定的默认值,但修改的时候 始终无法根据后端传回的值显示对应选项。向前端请教,确认后端传回的值无误后,就得将传回的值与option选项绑定(之前正是此处出错),正确代码如下。

前端jsp页面

<form method="post" action="${ctx}/saveFunc" class="layui-form" onsubmit="return validateCallback(this, dialogAjaxDone);">
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: auto;">姓名:</label>
        <div class="layui-input-block">
            <input type="text" size="40" name="name" class="layui-input" style="width: 97%;" value="${item.name}" lay-verify="checkName"/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">期望分数:</label>
        <input type="hidden" id="selectScore" value="${item.score}">
        <div class="layui-input-block">
            <select name="expecScore">
            	<%--  使用selected 将后端传回的值item.score与option选项绑定    --%>
                <option value="-1" <c:if test="${item.score == '-1'}">selected="selected"</c:if>>请选择分数</option>
                <option value="1" <c:if test="${item.score == '1'}">selected="selected"</c:if>>绩点A-90分以上</option>
                <option value="2" <c:if test="${item.score == '2'}">selected="selected"</c:if>>绩点B-8090分</option>
                <option value="3" <c:if test="${item.score == '3'}">selected="selected"</c:if>>绩点C-7080分</option>
                <option value="4" <c:if test="${item.score == '4'}">selected="selected"</c:if>>绩点D-6070分</option>
                <option value="5" <c:if test="${item.score == '5'}">selected="selected"</c:if>>绩点E-5060分</option>
                <option value="6" <c:if test="${item.score == '6'}">selected="selected"</c:if>>绩点F-50分以下</option>
            </select>
        </div>
    </div>
</form>

后端直接将score值传给前端(前端可直接调用)

@ResponseBody
public xxx getAllInfo(Model model, String name, String mode) {
	//xxx
    model.addAttribute("name", name);
    model.addAttribute("score", score);
    //xxx
}

三、运行结果

新增: 显示设定的默认值 在这里插入图片描述

修改: 根据后台传回的值选中 在这里插入图片描述