-1

I am new to MongoDB. My application is dynamic form builder that lets users add dynamic fields on the form. None of the field on the form is fix or static. The user can add any number and any type of fields such as Textbox, Textarea, Dropdown, Checkbox, Radiobutton etc fields on the form and save the form.

Now want to store the created fields into Database. then saved forms will be used to collect data from the users.

How to pass the Fields from the View to the controller? and to describe a Model and Controller for this (to handle fields)?

I’m using ASP.NET MVC as a frontend MongoDB as a backend

I'm pushing all the fields here:

$('.field').each(function() {

    var $this = $(this);

    //field type
    var fieldType = $this.data('type');

    //field label
    var fieldLabel = $this.find('.field-label').val();

    //field required
    var fieldReq = $this.hasClass('required') ? 1 : 0;

    //check if this field has choices
    if($this.find('.choices li').length >= 1) {

        var choices = [];

        $this.find('.choices li').each(function() {

            var $thisChoice = $(this);

            //choice label
            var choiceLabel = $thisChoice.find('.choice-label').val();

            //choice selected
            var choiceSel = $thisChoice.hasClass('selected') ? 1 : 0;

            choices.push({
                label: choiceLabel,
                sel: choiceSel
            });

        });
    }

    fields.push({
        type: fieldType,
        label: fieldLabel,
        req: fieldReq,
        choices: choices
    });
});

Saving Form with Dynamic fields:

var formArray=[];
  formArray.push({ name: "formID", value: "formID" }, { name: "formFields", value: "fields" });
  var formObject = JSON.stringify(formArray);
          $.ajax({
              method: "POST",
              url:'@Url.Action("Index", "Home")',
              data: formObject,
              dataType: 'JSON',
              success: function (data)
              {
                  console.log(data);
                  $('.alert').removeClass('hide');
                  $("html, body").animate({ scrollTop: 0 }, "fast");

                  //Demo only
                  $('.alert textarea').val(JSON.stringify(fields));
              }
          });

Can anyone suggest a Model and Controller for this?

Update

As @stom suggested, I did the following corrections:

Model

namespace Simple_jQuery_Form_Builder.Models
{
    public class ControlsAttribute
    {
        public string id { get; set; }
        public string value { get; set; }
        public string name { get; set; }
    }
    public class FormControl:ControlsAttribute
    { 
        public object textBox { get; set; }
        public object textArea { get; set; }
        public object checkBox { get; set; }
        public object radioButton { get; set; }
        public object agreeBox { get; set; }
        public object selectBox { get; set; }
        public object datePicker { get; set; }
    }
    public class Simple_jQuery_Form_Builder_Model
    {
        public List<FormControl> controls { get; set; }
        public List<FormControl> formEditor { get;set; }

    }

}

View

 <form method="post" action="~/Controllers/Home/Index">
                <div id="sjfb" novalidate>
                    <div id="form-fields">
                        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
                        {
                            @Html.DisplayFor(model => model.controls);
                            @Html.DisplayFor(model => model.formEditor);
                        }
                    </div>
                    <button type="submit" class="submit">Save Form</button>
                </div>
            </form>

Controller

[HttpPost]
public ActionResult Index(Simple_jQuery_Form_Builder_Model model)
{
    if (model != null)
        return Json("success");
    else
        return Json("An error has occured");
}

It's supposed to show the saved form in the desired link/div. It shows "success" message. Now I've to show the created form in another view (like the preview)

halfer
  • 19,824
  • 17
  • 99
  • 186
Iswarya
  • 9
  • 2
  • 1
    Your json binds to a model which has properties `string Name` and `string Value` - and in the POST method would be `public ActionResult(IEnumerable model)` You also need to set `contentType: 'application/json'` for that to bind to the model. –  Mar 23 '18 at 07:36
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Mar 23 '18 at 10:30
  • @Iswarya , your recent edits have lots issues, **1.** your models don't have any relation's. **2.** Using `@Html.DisplayFor` will not allow to post values to action method instead use `@Html.HiddenFor` , there are lot code to do provide solution,which not possible now. Advice You to learn `MVC` and `Jquery` Basics from [here](http://csharp-video-tutorials.blogspot.in) and go further. Also please format your edit properly so it is readable to others. – Shaiju T Mar 23 '18 at 11:45

1 Answers1

1

First create your View Models.

public class FormViewModel
{
    public string name { get; set;}
    public string value { get; set;}
}

Action methods

This is to load your form in GET request.

public ActionResult Index()
    {
        return View();
    }

This is to post your data in POST request.

 [HttpPost]
 public ActionResult SaveForm(IEnumerable<FormViewModel> model)
  {
        if (model != null)
        {
            return Json("Success");
        }
        else
        {
            return Json("An Error Has occoured");
        }

   }

Index View

Add this in your Index.cshtml View

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {

    $('#saveInMongo').click(function (e) {

      var formArray=[];

          formArray.push({ name: "formID", value: "formID" }, { name: "formFields", value: "fields" });
      var formObject = JSON.stringify(formArray);

            $.ajax({
                url: "@Url.Action("Home","SaveForm")",
                type: "POST",
                data: formObject,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (response) {
                    alert(response.responseText);
            },
                success: function (response) {
                    alert(response);
                }
            });

        });
    });
</script>

<input type="button" value="Save In Mongo" id="saveInMongo" />

This should work.

Check this for more.

Shaiju T
  • 6,201
  • 20
  • 104
  • 196
  • Thank you for your immediate response @stom :) – Iswarya Mar 23 '18 at 09:26
  • @Iswarya , If you found this answer helpful then upvote it or accept the answer by ticking the tick mark on the left of the answer. – Shaiju T Mar 23 '18 at 09:31
  • I'm having some doubts. how can I reply to you? I can't raise another Question as well. The comment section has restricted no. of words. How can I able to rectify my doubts? – Iswarya Mar 23 '18 at 10:11
  • @Iswarya you can edit your question and add more information on what problem your facing so that others can help you too or you can ask one at a time in comments. – Shaiju T Mar 23 '18 at 10:27