Search code examples
c#asp.netmodel-view-controllerdata-bindinghidden-field

asp.net mvc 4 data not binding


i'm currently working on a use case where the user take a snapshot with his webcam, the snapshot is then displayed along with a form generated in javascript containing one hidden field (with the base64 code of the snapshot) and one submit button.

Problem is, the action do get called but the model is empty...I've been locked on this for multiple hours...

Datamodel :

namespace backend_OCR.Models
{
    public class SnapshotModels
    {
        public string data_uri { get; set; }
    }
}

Controller :

    public ActionResult Capture()
    {
        ViewBag.uri = "URI_test";
        return View();
    }

    [HttpPost]
    public ActionResult Capture(SnapshotModels snapshot)
    {

        ViewBag.uri = snapshot.data_uri;

        return View();
    }

View :

@model backend_OCR.Models.SnapshotModels
@{
ViewBag.Title = "Capture";
}
<script type="text/javascript" src="~/Content/js/webcamjs.js"></script>

<div class="content-wrapper">
    <div class="col-md-6">
        <div class="panel panel-default">
        <div class="panel-heading">Camera</div>
        <div class="panel-body">
            <div class="container" id="my_camera"></div>
            <!-- A form for taking snaps and processing them-->
            <form style="text-align: center; margin-top: 10px;">
                <input style="text-align: center;" type="button" class="btn btn-success" value="Prendre capture" onclick="take_snapshot()">
            </form>

        </div>
    </div>
</div>
<div class="col-md-6">
    <div class="panel panel-default">
        <div class="panel-heading">Snapshot</div>
        <h2>@ViewBag.uri</h2>
        <div class="panel-body">
            @using (Html.BeginForm("Capture", "Camera", FormMethod.Post))
            {
            <div id="results" style="text-align: center;">
                L'image capturée apparaitra ici...
            </div>
            }
        </div>
        <br />
    </div>
</div>

Javascript :

<script language="JavaScript">
Webcam.set({
    width: 400,
    height: 300,
    image_format: 'jpeg',
    jpeg_quality: 100
});
Webcam.attach('#my_camera');
</script>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
    // take snapshot and get image data
    Webcam.snap(function (data_uri) {
        // display results in page
        document.getElementById('results').innerHTML =
            '<div><img id="my_snap" src="' + data_uri + '"/></div>'
            + '<input type="hidden" value="' + data_uri + '">'
            + '<input id="save" class="btn btn-success" value="Crop and  send" type="submit"/>';
</script>

Solution

  • You didn't assign any ID/Name to your '<input type="hidden" value="' + data_uri + '">' so the binder doesn't know how to bind it to your model and its property. it should have the same name/id your c# model class uses