简体   繁体   中英

ASP.NET MVC Get value of div by using ID in Controller

When the user clicks a button, the following HTML gets added to the page by Javascript, and the value of IncrNumber increases each time the button is clicked, so the first click would produce divs with the following ID's: (start0, end0, comm0) and the second click would produce ID's (start1, end1, comm1) and so on.

Start: <input type="text" class="form-control" id="start' + IncrNumber + '"/>

End: <input type="text" class="form-control" id="end' + IncrNumber + '" />

Comment:  <textarea rows="4" class="form-control" id="comm' + IncrNumber + '"></textarea>

Since these divs are being dynamically added with Javascript, I cannot use Razor and therefore cannot convert these text boxes into "HTML.TextBoxFor(x.start)..."

Since clicking a button will generate a variable, unlimited number of these fields, I cannot add them to my Model , anyways.


How can I get the values of startX, endX, and commX in my controller?

EDIT :

在此处输入图片说明

There exists a Many-To-One relationship between DBO.Televiewers[ID, Date] and DBO.Annotations[ID, TeleviewerID, Start, End, Comment]. The user can add as many Annotation objects as they want per Televiewer.

VIEW:

<div class="panel panel-form-5">
<div class="panel-heading">
    <h3 class="panel-title">Edit Televiewer</h3>
</div>
<div class="panel-body">

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()


        @Html.Label("Hole Name")
        @Html.EditorFor(m => m.HoleName, new { htmlAttributes = new { @class = "form-control" } })
        <br />
        @Html.Label("Televiewer Date")
        @Html.EditorFor(m => m.TeleviewerDate, new { htmlAttributes = new { @class = "form-control" } })
        <br />
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-10">
                        <h4>Annotations</h4>
                    </div>
                    <div class="col-lg-2">                           
                        <div id="addbuttondiv">
                            <button onclick="addAnswer(); return false;" class="btn btn-default">Add New</button>
                        </div>

                    </div>
                </div>
                <hr />
                <div id="annotations">


                </div>
            </div>
        </div>
        <br />
                @Html.ActionLink("Back", "Index", "Televiewer", null, new { @class = "btn btn-default" })
                <input type="submit" value="Calculate & Save" class="btn btn-primary" />
       }

            </div>
        </div>
        <script>
            var answers = 0;

            function addAnswer() {
                var write = document.getElementById('annotations');
                write.innerHTML += ' <div class="row"><div class="col-lg-3 col-lg-offset-1">Start Depth: <input type="text" class="form-control" id="start' + answers + '"/></div><div class="col-lg-3 col-lg-offset-4" >End Depth: <input type="text" class="form-control" id="end' + answers + '" /></div></div><br /><div class="row"><div class="col-lg-1 col-lg-offset-2"><br />Comment:</div><div class="col-lg-6"><textarea rows="4" class="form-control" id="comm' + answers + '"></textarea></div></div><hr/>';
                answers++;
            }
        </script>

There is no problem in sending back the newly created elements on the client as long as you support them on your model.

        $("#submit").on('click', function ()
        {
            var i = 0;
            $('input[name ^= \'start\']').remove();
            $('input[name ^= \'start\']').each(function ()
            {
                $("<input type='hidden' value='" + $(this).attr("id") + "' />").attr("id", "start_" + i + "_"+i).attr("name", "start[" + i + "]."+i).appendTo("form");
                i++;
            });

This will take care, on the client, to generate the object for your Model. You will need a list of start, end and comment lists for this or you can create a list that contains all three objects but you will need to change the object you send back from the client.

When you need to render those items:

<h5>Elements assigned here</h5>
<ul id="xxx" class="droptrue dropZone selectorBox list">
@foreach(var item in Model.startObjects)
{
  <li class="ui-state-default" id="@item.startID"><span class="sName2"><i class="fa fa-flask" aria-hidden="true"></i>&nbsp;@item.startName</span></li>
}
</ul>

Hope this helps!

Taking an approach similar to this story: MVC Form not able to post List of objects

Here are the basic models:

public class Televiewer
{

    public string HoleId { get; set; }

    public DateTime Date { get; set; }

    public List<Annotation> Annotations { get; set; }
}

public class Annotation
{
    public int AnnotationId { get; set; }
    public string HoleId { get; set; } //---- foreign key
    public int StartDepth { get; set; }
    public int EndDepth { get; set; }
    public string Comment { get; set; }
}

In the html, for your 'Annotations" section:

<div id="Annotations">
    @foreach (var ann in Model.Annotations)
    {
       <div class="annotation">
         <input type="text" class="form-control startDepth" name="Annotations[@i].StartDepth" value="@Model.Annotations[i].StartDepth" />
         <input type="text" class="form-control endDepth" name="Annotations[@i].EndDepth" value="@Model.Annotations[i].EndDepth" />
         <textarea rows="4" class="form-control comment"name="Annotations[@i].Comment" >@Model.Annotations[i].Comment</textarea>
       </div>
     }
</div>

In the javascript, when you click the "Add" button:

function addAnswer()
{
    var index = $('#Annotations').find('.annotation').length;
    var html = '<br><div class="annotation">'
            + '<input type="text" class="form-control startDepth" name="Annotations[' + index + '].StartDepth" value="" />'
            + '<input type="text" class="form-control endDepth" name="Annotations[' + index + '].EndDepth" value="" />'
            + '<textarea rows="4" class="form-control comment"name="Annotations[' + index + '].Comment" ></textarea>'
            + '</div>';
    $('#Annotations').append(html);
}

That should roughly plug in to your form submit. You may have to iron out a few kinks (can't say what because I don't have enough of your code).

Notes: 1. View models are your friend. If you need to wrap up some data, make a model for it. 2. Creating the html in the javascript the way I did is ok but using html templates would be better. I just didn't want to open that can or worms here. 3. The models I used are obviously stripped down. I'm assuming you are using EF though so you'll have to adjust accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM