0

How to insert data from ViewBag.Data into the database. Because dynamic textboxes work fine and transfer data to the controller. But I can not understand how data can be inserted into the database. On this line Symptom = _sumptomss , the data just disappears. And no matter how I tried to compare or transfer them, they are not transmitted.

Controller

#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);
}

model

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; }

    }
}

View

@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
  • Is _sumptomss a typo (I assumed it is _sumptoms)? Why not just assign like this: var _sumptoms = string.Join(",", dynamicField ?? new string[] { }); (because ViewBag is dynamic and may lose its content immediately after view rendering)? Commented Jul 16, 2018 at 5:58

1 Answer 1

2

The values of received string array is serialized into a JSON string using JavaScriptSerializer and then the JSON string is assigned to a ViewBag object named Values for recreation of dynamic TextBoxes after Form submission is completed.

You will need to import the following namespace.

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>

and you can split

    foreach (string textboxValue in dynamicField)
    {
        //save to db
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.