【问题标题】:script for window.location.href errorwindow.location.href 错误的脚本
【发布时间】:2017-05-18 12:56:28
【问题描述】:

这个问题是这个问题的继续first qestion 我有一个表单,我需要使用表单上传的详细信息重定向到操作(就像在 stackoverflow 中一样),但显然因为我使用的是 Ajax,它阻止了它从重定向,我试图添加我的 Ajax 重定向,但我不断收到错误和错误的 Url。它应该从 http://localhost:1914/En/VoosUp/Create 重定向到 http://localhost:1914/En/events/Index/42 (例如 ID 号)我用我写的内容得到的结果在我的 Js 代码中 如何将其重定向到正确的 url (Events/Index/Id) 提前致谢 js

function GetLocation() {
    var geocoder = new window.google.maps.Geocoder();

    var street = document.getElementById('txtAddress').value;
    var city = document.getElementById('txtCity').value;
    var address = city + street;
    console.log(address);
    var labelLat = document.getElementById('Latitude');
    var labellong = document.getElementById('longitude');

    geocoder.geocode({ 'address': address },
        function(results, status) {
            if (status == window.google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                console.log("Latitude: " + latitude + "\nLongitude: " + longitude); //Ok.

                labelLat.value = latitude; //Ok.
                labellong.value = longitude;
                var form = $('#RestoForm')[0];
                var formData = new FormData(form);
                $.ajax({
                    url: 'Create',
                    type: 'POST',
                    contentType: false,
                    processData: false,
                    data: formData,
                    datatype: "html",
                    success: function(data) {
                        $('#RestoForm').html(data),
                            //   window.location.href = '@Url.Content:("~/Events/Index")' + "Id";
                            //= A potentially dangerous Request.Path value was detected from the client (:).
                            // En/VoosUp/@Url.Content:("~/Events/Index")Id
                            window.location.href = '@Url.Action("~/Events/Index")';
                        // =The resource cannot be found >
                        //En/VoosUp/@Url.Action("Events/Index 

                    }

                });

                error: function e(xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            }
        });
};` 

控制器:

 [Authorize]
    public ActionResult Create()
    {
        var viewModel = new LectureFormViewModel
        {
            Genres = _context.Genres.ToList(),

        };
        return View("Gigform", viewModel);
    }

    [Authorize, HttpPost]
    public ActionResult Create(LectureFormViewModel viewModel)
    {

        if (!ModelState.IsValid)
        {
            viewModel.Genres = _context.Genres.ToList();

            return View("Gigform", viewModel);
        }


        var lectureGig = new LectureGig
        {
           //Parameters
        };

        _context.LectureGigs.Add(lectureGig);
        _context.SaveChanges();

        // return this.RedirectToAction( "events", (c=>c.Index(lectureGig.Id));
        return RedirectToAction("index", "Events", new { id = lectureGig.Id });
    }

和目标

 public ActionResult Index(int id)
    {
        var lecturegig = _context.LectureGigs.Include(g => g.Artist)
           .Include(g => g.Genre)
           .SingleOrDefault(g => g.Id == id);
        if (lecturegig == null)
            return HttpNotFound();
        var viewmodel = new GigDetailViewModel { LectureGig = lecturegig };

        return View("index", viewmodel);
    }

【问题讨论】:

  • '@Url.Action("Index", "Events")';
  • @Satpal localhost:1914/En/VoosUp/… > window.location.href= '@Url.Action("Index", "Events")';也不适合我
  • 试试这个 - window.location.href= @String.Concat("'", Url.Action("Index", "Events"), "'");
  • @majita 它在某处缺少引用&我找不到 >Url 未定义的位置
  • 只是一个愚蠢的问题:Ajax 旨在避免重定向。您想要做的事情可以通过简单的表单提交来完成。为什么需要模拟纯表单提交(用Ajax发帖,然后重定向)?

标签: javascript jquery ajax asp.net-mvc redirect


【解决方案1】:

如果您的 JavaScript 在 cshtml 中,应该这样做:

   var id = 1;
   var url = '@Url.Action("Index", "Events")';
   window.location.href = url + "/" + id;

但是根据您的描述,您似乎正试图从一个不知道 MVC 助手的 .js 文件调用它,因此您可以尝试这样的事情:

var id = 1; 

var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

window.location.href = baseUrl + '/Events/Index' + id;

要获得正确的 Id,请修改您的操作以返回 Id,例如

public JsonResult Create(LectureFormViewModel viewModel)
{
   return Json(new { Id=lectureGig.Id });
}

然后您可以在 JavaScript 中访问此 ID,例如

 success: function(data) {
   var id = data.Id;
 }

【讨论】:

  • 这把我带到localhost:1914/En/VoosUp/… & 请求 URL 是(它的 404)/En/VoosUp/@Url.Action("Index", "Events")/1
  • @AssafOur 编辑了我的答案以适应 .js 文件
  • 我们到了那里,我不知道如何使用 json,所以我使用了在 Chtml 文件中添加脚本的选项,我得到的 url 没有索引并且 Id 仍然是静态的(1) 现在看起来像:localhost:1914/En/Events/1
  • @AssafOur 您需要从服务器(即您的控制器创建操作)中取回 Id。有多种方法可以做到这一点,但这里是一个使用 json 的示例 - stackoverflow.com/a/11267280/2401021 您需要将 ajax 请求的数据类型从 html 更改为 json 才能正常工作
【解决方案2】:

如果是cshtml文件,可以使用代码

window.location.href = '@Url.Action("Index", "Events")'+ "?id=1";

如果你在js文件中

window.location.href='/Events/Index?id=1'

【讨论】:

  • Js 文件中的 window.location.href='/Events/Index?id=1' 让我进入 localhost:1914/Events/Index?id=1 (请注意缺少全球化(En),加上 id静态 1 ,而不是新的 Id 。应该是 ../En/Envets/Index/1 (动态 Id) .thnks
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 2018-05-07
  • 2013-01-05
  • 2018-08-29
  • 2012-10-13
  • 2020-12-10
相关资源
最近更新 更多