如何将选定的复选框ID保存到MVC中的数据库 [英] How can I save the selected checkbox id to database in MVC

查看:67
本文介绍了如何将选定的复选框ID保存到MVC中的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将选中的复选框ID保存到数据库。模型类是

公共部分类映射
{
public int Id {get;组; }
public Nullable< int> DistrictId {get;组; }
public Nullable< int> PostId {get;组; }
public List< string> GetAllSelctedCheckBoxes {get;组; }
}

除了

 public List< string> GetAllSelctedCheckBoxes {get;组; } 

所有其他字段绑定到数据库。

查看页面是

< div class =form-group> 
@ Html.Label(District,htmlAttributes:new {@class =control-label col-md-2})
< div class =col-md-10>
@ Html.DropDownList(DistrictId,ViewBag.DistrictId as SelectList, - 请选择 - ,新{style =width:250px})
< / div>
< / div>

< div class =form-group> 
@ Html.LabelFor(model => model.PostId,PostName,htmlAttributes:new {@class =control-label col-md-2})
< div class = COL-MD-10\" >
< div id =PostMaster>< / div>
@ Html.HiddenFor(m => m.GetAllSelctedCheckBoxes)
@ Html.ValidationMessageFor(model => model.PostId,,new {@class =text-danger})
< / div>
< / div>

< div class =form-group> 
< div class =col-md-offset-2 col-md-10>
< input type =submitvalue =创建class =btn btn-defaultid =创建/>
< / div>
< / div>
< / div>

< script type =text / javascript> 
$(document).ready(function(){
// District Dropdown Selectedchange事件
$(#DistrictId)。change(function(){
$( #PostMaster)。empty();
$ .ajax({
type:'POST',
url:'@ Url.Action(GetPosts)',//调用json方法
dataType:'json',
data:{id:$(#DistrictId)。val()},
//获取选定的帖子ID。
成功: function(posts){
$ .each(posts,function(i,post){

$(#PostMaster)。append('< input type =checkboxname =postdatavalue ='+ post.Text +'>'+ post.Text +'< br>');
});
},
错误:function( ex){
alert('无法检索帖子。'+ ex);
}
});
返回false;
})
} );
< / script>
< script>
$(#Create)。click(function(){
$('#GetAllSelctedCheckBoxes')。empty();
debugger;
var getList = [];
$(#PostMaster输入:选中)。each(function(){
getList.push($(this).val());
var form =($(this ).val());
});
$('#GetAllSelctedCheckBoxes')。val(getList); //分配给隐藏字段
});
< / script>



这是我的查看页面,在这里我可以选中复选框,所选复选框显示在

 GetAllSelctedCheckBoxes 

中传递给控制器​​的httpPost参数。

 [HttpPost] 
[ValidateAntiForgeryToken]
public async Task< ActionResult>创建(映射映射)
{
if(ModelState.IsValid)
{
db.Mappings.Add(mapping);
等待db.SaveChangesAsync();
返回RedirectToAction(Index);
}
return View(mapping);
}





但是我无法将所选值存储到db。可以帮我解决所选项目将显示为字符串的问题,我需要将其保存为整数。



我尝试过的方法:



我已多次尝试过,无法正确找到解决方案

解决方案

(document).ready(function(){
// District Dropdown Selectedchange事件


(#DistrictId)。change(function(){


( #邮局主管)空();

I am not able to save the checked checkbox id to database. Model class is

public partial class Mapping
    {
        public int Id { get; set; }
        public Nullable<int> DistrictId { get; set; }
        public Nullable<int> PostId { get; set; }
        public List<string> GetAllSelctedCheckBoxes { get; set; }
    }

except

public List<string> GetAllSelctedCheckBoxes { get; set; }

all other fields bind to database.
view page is

<div class="form-group">
            @Html.Label("District", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("DistrictId", ViewBag.DistrictId as SelectList, "-- Please Select  --", new { style = "width:250px" })
            </div>
        </div>

<div class="form-group">
            @Html.LabelFor(model => model.PostId,"PostName", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div id="PostMaster"></div>
                @Html.HiddenFor(m => m.GetAllSelctedCheckBoxes) 
                @Html.ValidationMessageFor(model => model.PostId, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" id="Create"/>
            </div>
        </div>
    </div>

<script type="text/javascript">
$(document).ready(function () {
    //District Dropdown Selectedchange event
    $("#DistrictId").change(function () {
        $("#PostMaster").empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetPosts")', // Calling json method
            dataType: 'json',
            data: { id: $("#DistrictId").val() },
            // Get Selected post id.
            success: function (posts) {
                $.each(posts, function (i, post) {

                    $("#PostMaster").append('<input type="checkbox" name="postdata" value=' + post.Text + '>' + post.Text + '<br>');                   
                });
            },
            error: function (ex) {
                alert('Failed to retrieve post.' + ex);
            }
        });
        return false;
    })
});
</script>
<script>
$("#Create").click(function () {
       $('#GetAllSelctedCheckBoxes').empty();
            debugger;
            var getList = [];
            $("#PostMaster input:checked").each(function () {
                getList.push($(this).val());
                var form = ($(this).val());
            });
            $('#GetAllSelctedCheckBoxes').val(getList);// assign to hidden field
   });
</script> 


this is my view page, here I can check the checkbox and the selected checkbox is displayed in

GetAllSelctedCheckBoxes

and this is passing to the httpPost parameter of the controller.

[HttpPost]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Create(Mapping mapping)
       {
          if (ModelState.IsValid)
           {
               db.Mappings.Add(mapping);
               await db.SaveChangesAsync();
               return RedirectToAction("Index");
           }
           return View(mapping);
       }



but I am not able to store the selected value to db . can sombody please help me to get solution that the selected item will display as string and I need to save it as interger.

What I have tried:

I have tried many times and cannot find a solution correctly for my problem

解决方案

(document).ready(function () { //District Dropdown Selectedchange event


("#DistrictId").change(function () {


("#PostMaster").empty();


这篇关于如何将选定的复选框ID保存到MVC中的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆