首页 > 解决方案 > 动态添加文本框并在数据库中保存数据

问题描述

如何将数据从ViewBag.Data数据库中插入。因为动态文本框可以正常工作并将数据传输到控制器。但我不明白如何将数据插入数据库。在这条线上Symptom = _sumptomss,数据就消失了。而且无论我如何尝试比较或传输它们,它们都不会被传输。

控制器

#region public ActionResult Create()
public ActionResult Create(string[] dynamicField)
{
    DiseaseDetails objDiseaseDetails = new DiseaseDetails();
    ViewBag.Data = string.Join(",", dynamicField ?? new string[] { });
    return View(objDiseaseDetails);
}
#endregion

[HttpPost]
[ValidateAntiForgeryToken]
#region public ActionResult Create(DiseaseDetails objDiseaseDetails)
public ActionResult Create(DiseaseDetails diseaseDetails, string[] dynamicField)
{
    if (diseaseDetails == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var DiseaseName = diseaseDetails.DiseaseName.Trim();
    ViewBag.Data = string.Join(",", dynamicField ?? new string[] { });
    var _sumptoms = ViewBag.Data;

    var objNewDisease = new DiseaseDetails
    {
        DiseaseName = DiseaseName,
        Symptom = _sumptomss,
    };

    if (ModelState.IsValid)
    {
        db.DiseaseDetails.Add(objNewDisease);

        try
        {
            db.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);

                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                }
            }

            throw;
        }

        return RedirectToAction("Index");
    }

    ModelState.AddModelError("", "Something going wrong");
    return View(diseaseDetails);
}

模型

namespace IdentitySample.Models
{

    public class DiseaseDetails
    {
        [Key]
        public int DiseaseId { get; set; }

        [Required]
        [Display(Name = "Symptoms")]
        public string Symptom { get; set; }

        [Required]
        [Display(Name = "Disease Name")]
        public string DiseaseName { get; set; }

    }
}

看法

@model IdentitySample.Models.DiseaseDetails
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
@using (Html.BeginForm("Create", "DiseaseDetails", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h3>Fill up disease details:</h3>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.DiseaseName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DiseaseName, new { htmlAttributes = new { @class = "form-control", autocomplete = "off" } })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Symptom, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10" id="fields">
            @Html.HiddenFor(model => model.Symptom, new { htmlAttributes = new { @class = "form-control", autocomplete = "off" } })
            <input type="text" name="dynamicField" id="symptom" autocomplete="off" class="form-control" /><br />
        </div>
        <div class="col-md-10" align="center">
            <button id="btnAddField" class="btn btn-default">Add Field</button>
        </div>
    </div>
}
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script type="text/javascript">

    $(document).ready(function () {
        var $fields = $('#fields');
        $('#btnAddField').click(function (e) {
            e.preventDefault();
            $('<input type="text" name="dynamicField" autocomplete="off" class="form-control"/><br/>').appendTo($fields);
        });
    });
</script>

标签: jquerysqlasp.net-mvc

解决方案


接收到的字符串数组的值使用序列化为 JSON 字符串JavaScriptSerializer,然后将 JSON 字符串分配给名为 Values 的 ViewBag 对象,以便在表单提交完成后重新创建动态文本框。

您将需要导入以下命名空间。

using System.Web.Script.Serialization;


 @using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
    <input id="btnAdd" type="button" value="Add" onclick="AddTextBox()"/>
    <br/>
    <br/>
    <div id="TextBoxContainer">
        <!--Textboxes will be added here -->
    </div>
    <br/>
    <input type="submit" value="Submit"/>
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    function GetDynamicTextBox(value) {
        var div = $("<div />");

        var textBox = $("<input />").attr("type", "textbox").attr("name", "dynamicField");
        textBox.val(value);
        div.append(textBox);

        var button = $("<input />").attr("type", "button").attr("value", "Remove");
        button.attr("onclick", "RemoveTextBox(this)");
        div.append(button);

        return div;
    }
    function AddTextBox() {
        var div = GetDynamicTextBox("");
        $("#TextBoxContainer").append(div);
    }

    function RemoveTextBox(button) {
        $(button).parent().remove();
    }

    $(function () {
        var values = eval('@Html.Raw(ViewBag.Values)');
        if (values != null) {
            $("#TextBoxContainer").html("");
            $(values).each(function () {
                $("#TextBoxContainer").append(GetDynamicTextBox(this));
            });
        }
    });
</script>

你可以分开

    foreach (string textboxValue in dynamicField)
    {
        //save to db
    }

推荐阅读