简体   繁体   English

AJAX请求加载的局部视图-MVC

[英]AJAX request for a loaded partial view -MVC

The concept behind my question is that whenever a value is shown in my ID textbox, that value id pulls the information corresponding to that ID in a partial view to the right of the page via AJAX and Javascript. 我的问题背后的概念是,每当在我的ID文本框中显示一个值时,该值id就会通过AJAX和Javascript在页面右侧的部分视图中提取与该ID对应的信息。

I currently have the partial view showing on the right but there is an error alert by chrome that it cant populate the partial view, so it just shows the empty partial view (textbox etc). 我目前在右侧显示部分视图,但是chrome发出错误警报,提示它无法填充部分视图,因此它仅显示空的部分视图(文本框等)。 I've tried researching my problem but cant find anything relating to the html.partial() instead has tutorials on views already in the page which i don't want. 我已经尝试研究我的问题,但找不到与html.partial()相关的任何内容,而是在页面中已有了我不想要的关于视图的教程。 Any ideas on where i am going wrong? 对我要去哪里有任何想法吗? below is my code regarding the issue. 以下是我关于此问题的代码。

Im still getting to grips with AJAX so apologies for any silly mistakes. 我仍然对AJAX有所了解,因此对任何愚蠢的错误表示歉意。

Jobscanner.cshtml Jobscanner.cshtml

<div id="QR">
    <div id="first">
        <p>Hold a QR Code in front of your webcam.</p>

        <video id="camsource" autoplay="" width="320" height="240">Webcam has failed, Please try another</video>
        <canvas id="qr-canvas" width="320" height="240" style="display:none"></canvas>
  @* <div class="hidden">*@
     <input type="text" id="qr-value"  value=""  placeholder="Scanned QR Code..." />
             <input type="text" id="qr-number"  value="" placeholder="Job ID...." />
     <button>Reset Scan</button>
 @* </div>*@
    </div>
    <div id="second">
     <div id='Sample'>
          <p class="hide">@Html.Partial("CameraInfo")</p> 
     </div>
    </div>
</div>

QRView.js QRView.js

    $(document).ready(function () {
    $("#QR").show(1000);
    $("button").click(function () {
        $("#qr-value").val("")
        $("#second").hide(500);
    });
});

$(document).ready(function () {
    $('#qr-value').on('change', function () {
        var string = $('#qr-value').val();

        if (~string.indexOf('Job')) {
            var num = string.match(/\d+/g);
            $("#qr-number").val(num).change();
            $("#second").show(1000);
        } else {
            $("#qr-number").val("")
            $("#second").hide(500);
        }
    });
});


$(document).ready(function () {
    $('#qr-value').on('change', function () {
        $.ajax({
            type: "Get",
            url: '@Url.Action("Edit", "CameraInfo")',
            data: { id: $('#qr-number').val() },
            success: function (response) {
                $('#Sample').html(response);
            },
            error: function (response) {
                if (response.responseText != "") {
                    alert(response.responseText);
                    alert("Some thing wrong..");
                }
            }
        });
    });
});

camerainfo.cshtml (partial view) camerainfo.cshtml(部分视图)

     @model JobTracker.Models.Job

    <h2>Edit and Confirm</h2>

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)

        <fieldset>
            <legend>Job</legend>

    @*        @Html.HiddenFor(model => model.JobID)

          <div class="editor-label">
                @Html.LabelFor(model => model.LocationID, "Location")
            </div>
            <div class="editor-field">
                @Html.DropDownList("LocationID", String.Empty)
                @Html.ValidationMessageFor(model => model.LocationID)
            </div><br />*@

            <div class="editor-label">
                @Html.LabelFor(model => model.HighPriority)
            </div>
            <div class="editor-field">
                @Html.DropDownListFor(model => model.HighPriority, new SelectList(
            new[] 
            { 
                new { Value = "Yes", Text = "Yes" },
                new { Value = "No", Text = "No" },
            },
             "Value",
             "Text",
            Model
        ))

                @Html.ValidationMessageFor(model => model.HighPriority)
            </div><br />

            <div class="editor-label">
                @Html.LabelFor(model => model.Comments)
            </div>
            <div class="editor-field">
                @Html.TextAreaFor(model => model.Comments)
                @Html.ValidationMessageFor(model => model.Comments)
            </div><br />

              <div class="editor-label">
                @Html.LabelFor(model => model.Status)
            </div>
            <div class="editor-field">
                   @Html.DropDownListFor(model => model.Status, new SelectList(
            new[] 
            { 
                new { Value = "In Progress", Text = "In Progress" },
                new { Value = "Completed", Text = "Completed" },
                new { Value = "Not Started", Text = "Not Started" },
                new { Value = "Stopped", Text = "Stopped" },
            },
             "Value",
             "Text",
            Model
        ))
                @Html.ValidationMessageFor(model => model.Status)
            </div><br />

            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>

    }




    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

CameraInfoController.cs CameraInfoController.cs

       [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            Job job = db.Jobs.Find(id);
            if (job == null)
            {
                return HttpNotFound();
            }
            ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", job.LocationID);
            ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", job.OrderID);

            return PartialView("CameraInfo", job);
        }

error from google 来自Google的错误

   <!DOCTYPE html>

<html>

    <head>

        <title>The resource cannot be found.</title>

        <meta name="viewport" content="width=device-width" />

        <style>

         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 

         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}

         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}

         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }

         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }

         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}

         .marker {font-weight: bold; color: black;text-decoration: none;}

         .version {color: gray;}

         .error {margin-bottom: 10px;}

         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }

         @media screen and (max-width: 639px) {

          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }

         }

         @media screen and (max-width: 479px) {

          pre { width: 280px; }

         }

        </style>

    </head>



    <body bgcolor="white">



            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>



            <h2> <i>The resource cannot be found.</i> </h2></span>



            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">



            <b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. &nbsp;Please review the following URL and make sure that it is spelled correctly.

            <br><br>



            <b> Requested URL: </b>/QR/@Url.Action(&quot;Edit&quot;, &quot;CameraInfo&quot;)<br><br>



            <hr width=100% size=1 color=silver>



            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212



            </font>



    </body>

</html>

<!-- 

[HttpException]: A public action method &#39;@Url.Action(&quot;Edit&quot;, &quot;CameraInfo&quot;)&#39; was not found on controller &#39;JobTracker.Controllers.QRController&#39;.

   at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)

   at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()

   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)

   at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()

   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)

   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)

   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()

   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)

   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)

   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

-->

I appreciate any feedback :) 我感谢任何反馈:)

I think the problem would be your url in the ajax - well actually I know since the error message also states it: 我认为问题可能是您在Ajax中的网址-实际上我知道,因为错误消息也指出了这一点:

The resource cannot be found. 无法找到该资源。
Requested URL: /QR/@Url.Action("Edit", "CameraInfo"). 请求的URL:/QR/@Url.Action("Edit“,” CameraInfo“)。

The reason is that Razor syntax is not recognized in that file. 原因是在该文件中无法识别Razor语法。

Either set a js-variable from the partial view, like: 从局部视图设置js变量,例如:

<!-- In the end of your partial view, or wherever you referense the js-file -->
<script type="text/javascript">
 var myJsUrl = '@Url.Action("Edit", "CameraInfo")';
</script>  
//In your JS-file, assuming this is referensed from your partial view
$.ajax({
        type: "Get",
        url: myJsUrl,
        ...

Or just type it by hand (the easiest solution): 或直接手动输入(最简单的解决方案):

    $.ajax({
        type: "Get",
        url: '/CameraInfo/Edit',
        ...

I should also say that there is no need to keep writing $(document).ready before each method/call. 我还应该说,无需在每个方法/调用之前继续写$(document).ready Just do it once, and put all code within the scope of that. 只需执行一次,然后将所有代码放入该范围内。

Edit: 编辑:

Also, you're binding two change events to the same textbox ( #qr-value ). 另外,您将两个更改事件绑定到同一个文本框( #qr-value )。 Merge the code and only keep one event: 合并代码,仅保留一个事件:

$(document).ready(function () {
  $('#qr-value').on('change', function () {

    var string = $('#qr-value').val();
    if (~string.indexOf('Job')) {
        var num = string.match(/\d+/g);
        $("#qr-number").val(num).change();
        $("#second").show(1000);
    } else {
        $("#qr-number").val("")
        $("#second").hide(500);
    }

    $.ajax({
        type: "Get",
        url: '/CameraInfo/Edit',
        data: { id: $('#qr-number').val() },
        success: function (response) {
            $('#Sample').html(response);
        },
        error: function (response) {
            if (response.responseText != "") {
                alert(response.responseText);
                alert("Some thing wrong..");
            }
        }
    });
  });
});    

Seems that your camerainfo file requires a "Job" model. 似乎您的camerainfo文件需要“作业”模型。 If you want to render partials and initiate the model using a controller, you can use 如果要渲染局部并使用控制器初始化模型,则可以使用

@{Html.RenderAction("actionName","controllerName")}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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