ASP.NET MVC2视图和部分表单中的奇怪行为

时间:2010-09-07 00:07:33

标签: asp.net-mvc asp.net-mvc-2

我正在ASP.NET MVC 2中实现MS NerdDinner应用程序,我正在使用谷歌地图而不是MS地图。我使用谷歌网站的示例代码来获取地图。我在同一目录中有2个非常简单的视图,Create.aspx和Edit.aspx,它们分别创建和编辑晚餐。它们非常简单 - 它们都呈现名为Dinner.ascx的部分视图,它也位于同一目录中。

晚餐表格包含3个js文件,还会显示另一个显示谷歌地图的部分表格。我有两个问题:

  1. 从“编辑”视图渲染时的晚餐表单找不到Javascript文件并且完全失败,而当从“创建”视图调用它时,正在查看Javascript文件并且正在进行操作。创建的网址为http://localhost/NerdDinner/Dinners/Create,编辑为http://localhost/NerdDinner/Dinners/Edit/39。为什么在编辑视图中找不到JS文件,即使两个视图都呈现相同的局部视图?

  2. 在Firefox(版本3.6.8)中,“创建”页面有时仅起作用,它非常不一致。通常在刷新几次或离开并返回页面后它最终会起作用,而在IE 8中它始终有效。 FF为何与此不一致?

  3. 解决方案目录结构是:

    NerdDinner(root)
      控制器
         - HomeController.cs
         - DinnersController.cs
         - 等
      模型
      脚本
         - CurrentJS.js
         - MainJS.js
         - jQuery-1.4.1.js
         - 等
      查看
         - 帐户
         - 晚餐
           - - Create.aspx
           - - Edit.aspx
           - - DinnerForm.ascx
           - - GoogleMap2.ascx
           - 等等      - 家庭
         - 共享

    我一直用头撞在墙上2天,看不见树木了。下面的代码(如果有点冗长则道歉):

    Create.aspx

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Controllers.DinnerFormViewModel>" %>
    <asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server">
        Host a Dinner
    </asp:Content>
    <asp:Content ID="Create" ContentPlaceHolderID="MainContent" runat="server">
        <h2>Host a Dinner</h2>
        <% Html.RenderPartial("DinnerForm"); %>
    </asp:Content>
    

    Edit.aspx:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Controllers.DinnerFormViewModel>" %>
    <asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server">
        Edit:
        <%=Html.Encode(Model.Dinner.Title) %>
    </asp:Content>
    <asp:Content ID="Edit" ContentPlaceHolderID="MainContent" runat="server">
        <h2>
            Edit Dinner</h2>
        <% Html.RenderPartial("DinnerForm"); %>   
    </asp:Content>
    

    DinnerForm.ascx:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<NerdDinner.Controllers.DinnerFormViewModel>" %>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="../Scripts/MainJS.js"></script>
    <script type="text/javascript" src="../Scripts/CurrentJS.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#Address").blur(function(evt) {
                $("#Latitude").val("");
                $("#Longitude").val("");
    
                var address = jQuery.trim($("#Address").val());
    
                alert('address: ' + address);
    
                if (address.length < 1)
                    return;
    
                codeAddress();
            });
        });
    </script>
    
    <%= Html.ValidationSummary("Please correct your errors and try again.") %>
    <% using (Html.BeginForm()) { %>
    <fieldset>
        <p>
            <label for="Title">
                Dinner Title:</label>
            <%= Html.TextBox("Title", Model.Dinner.Title) %>
            <%=Html.ValidationMessage("Title", "*") %>
        </p>
        <p>
            <label for="EventDate">
                Event Date:</label>
            <%= Html.TextBox("EventDate", Model.Dinner.EventDate) %>
            <%= Html.ValidationMessage("EventDate", "*") %>
        </p>
        <p>
            <label for="Description">
                Description:</label>
            <%= Html.TextArea("Description", Model.Dinner.Description) %>
            <%= Html.ValidationMessage("Description", "*") %>
        </p>
        <p>
            <label for="Address">
                Address:</label>
            <%= Html.TextBox("Address", Model.Dinner.Address) %>
            <%= Html.ValidationMessage("Address", "*") %>
        </p>
        <p>
            <label for="Country">
                Country:</label>
            <%= Html.DropDownList("Country", Model.Countries) %>
            <%= Html.ValidationMessage("Country", "*") %>
        </p>
        <p>
            <label for="ContactPhone">
                Contact Phone #:</label>
            <%= Html.TextBox("ContactPhone", Model.Dinner.ContactPhone) %>
            <%= Html.ValidationMessage("ContactPhone", "*") %>
        </p>
        <p>
            <%= Html.Hidden("Latitude", Model.Dinner.Latitude) %>
        </p>
        <p>
            <%= Html.Hidden("Longitude", Model.Dinner.Longitude) %>
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
    <div id="mapDiv">
        <%Html.RenderPartial("GoogleMap2", Model.Dinner); %>
    </div>
    <% } %>
    

    GoogleMap2.ascx:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>    
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0px; padding: 0px }
      #map_canvas { height: 50% }
      #infoPanel {
        float: left;
        margin-left: 10px;
      }
      #infoPanel div {
        margin-bottom: 5px;
      }
    </style>
    <!-- End add for google map -->
    
    <div id="map_canvas" style="width: 765px; height: 400px;">
    </div>
    
    <div id="infoPanel">
        <b>Marker status:</b>
        <div id="markerStatus">
            <i>Click and drag the marker.</i></div>
        <b>Current position:</b>
        <div id="info"></div>
        <b>Closest matching address:</b>
        <div id="address"></div>
    </div>
    
    <script type="text/javascript">
        $(document).ready(function() {
            initialize4();
        });
    </script>
    

    CurrentJS.js:

    //// +++++++++++ Start of attempt to pinpoint location automatically
    
    function initialize4() {
        var myOptions = {
            zoom: 9,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
        // Try W3C Geolocation (Preferred)     
        if (navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(initialLocation);
            }, function() {
                handleNoGeolocation(browserSupportFlag);
            });
            // Browser doesn't support Geolocation
        } else {
            browserSupportFlag = false;
            handleNoGeolocation(browserSupportFlag);
        }
    
        if (initialLocation == 'undefined')
            alert('1' + initialLocation);
        else
            alert('2' + initialLocation);
    
        //Add draggable marker
        var marker = new google.maps.Marker({
            position: initialLocation, //latLng,
            title: 'Point B',
            map: map,
            draggable: true
        });
    
        // Update current position info.
        updateMarkerPosition(initialLocation);
        geocodePosition(initialLocation);
    
        // Add dragging event listeners.
        google.maps.event.addListener(marker, 'dragstart', function() {
            updateMarkerAddress('Dragging...');
        });
    
        google.maps.event.addListener(marker, 'drag', function() {
            updateMarkerStatus('Dragging...');
            updateMarkerPosition(marker.getPosition());
        });
    
        google.maps.event.addListener(marker, 'dragend', function() {
            updateMarkerStatus('Drag ended');
            geocodePosition(marker.getPosition());
        });
    
        function handleNoGeolocation(errorFlag) {
            if (errorFlag == true) {
                alert("Geolocation service failed.");
                initialLocation = newyork;
            } else {
                alert("Your browser doesn't support geolocation. We've placed you in newyork.");
                initialLocation = newyork;
            }
            map.setCenter(initialLocation);
        }
    }
    
    function geocodePosition(pos) {
        geocoder.geocode({
            latLng: pos
        }, function(responses) {
            if (responses && responses.length > 0) {
                updateMarkerAddress(responses[0].formatted_address);
            } else {
                updateMarkerAddress('Cannot determine address at this location.');
            }
        });
    }
    
    function updateMarkerStatus(str) {
        document.getElementById('markerStatus').innerHTML = str;
    }
    
    function updateMarkerPosition(latLng) {
        //alert('latLng:' + latLng);
        document.getElementById('info').innerHTML = [
        latLng.lat(),
        latLng.lng()
      ].join(', ');
    }
    
    function updateMarkerAddress(str) {
        document.getElementById('address').innerHTML = str;
    }
    
    function codeAddress() {
        var address = document.getElementById("address").value;
    
        alert('In codeAddress');
    
        geocoder.geocode({ 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
    //// +++++++++++++ End attempt to pinpoint location automatically    
    

2 个答案:

答案 0 :(得分:0)

Q1:听起来很困惑在哪里可以找到javascript文件。

而不是

<script type="text/javascript" src="../Scripts/MainJS.js"></script>
<script type="text/javascript" src="../Scripts/CurrentJS.js"></script>

将这些更改为

<script type="text/javascript" src="/Scripts/MainJS.js"></script>
<script type="text/javascript" src="/Scripts/CurrentJS.js"></script>

这些行上的相对路径可能会有所不同,具体取决于当前正在呈现的视图或部分视图。

Q2:在Firefox(版本3.6.8)中,“创建”页面有时仅起作用 - 您能否进一步解释 - 当它不起作用时显示什么?

答案 1 :(得分:0)

我通过改变相对路径来修复js问题,使用下面的语法:

<script src='<%=ResolveClientUrl("~/Scripts/MainJS.js") %>' type="text/javascript"></script>