动态添加文本框并将数据保存在数据库中

时间:2018-07-16 04:24:22

标签: jquery sql asp.net-mvc

如何将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>

1 个答案:

答案 0 :(得分:2)

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

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

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
    }