0

this Q. is a continue of this question first qestion I have a form that I need to redirect to action with the form uploaded details (just like In stackoverflow) , but apparently because i'm using Ajax , it prevent it from redirect , I have tried to add my Ajax a redirect but I keep getting error and wrong Url . it should redirect from http://localhost:1914/En/VoosUp/Create To http://localhost:1914/En/events/Index/42 (E.G. Id number) the results i'm getting with what I wrote are in my Js Code How can I redirect it to the correct url (Events/Index/Id ) Thanks in advance 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);
                }
            }
        });
};` 

Controller:

 [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 });
    }

and the target

 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);
    }
Community
  • 1
  • 1
Assaf Our
  • 611
  • 3
  • 9
  • 25

2 Answers2

1

This should do it if your JavaScript is in the cshtml:

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

Based on your description however it seems that you are trying to call this from a .js file which has no idea about MVC helpers so instead you can try something like this:

var id = 1; 

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

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

To get the correct Id modify your action to return the Id e.g.

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

then you can access this Id in JavaScript e.g.

 success: function(data) {
   var id = data.Id;
 }
majita
  • 1,278
  • 14
  • 24
  • this bring me to http://localhost:1914/En/VoosUp/@Url.Action(%22Index%22,%20%22Events%22)/1 & request Url is (its a 404) /En/VoosUp/@Url.Action("Index", "Events")/1 – Assaf Our Jan 04 '17 at 10:30
  • @AssafOur have edited my answer to cater for .js file – majita Jan 04 '17 at 10:49
  • we are getting there , I wasn't sure how to use the json so I have use the option ofhaving the script on Chtml file, the url I get not has no index and the Id is still static (1)now it look like :http://localhost:1914/En/Events/1 – Assaf Our Jan 04 '17 at 11:05
  • @AssafOur You need to get the Id back from the server i.e. from your Controllers Create action. There are various ways to do this but here is an example using json - http://stackoverflow.com/a/11267280/2401021 you need to change the datatype of your ajax request from html to json for this to work – majita Jan 04 '17 at 11:16
0

If it is in a cshtml file you can use the code

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

If you are in js file

window.location.href='/Events/Index?id=1'
  • window.location.href='/Events/Index?id=1' in the Js file is getting me to http://localhost:1914/Events/Index?id=1 (Please note the globalizing (En) is missing , plus the id is static 1 ,and not the new Id .Should be ../En/Envets/Index/1 (the dynamic Id) .thnks – Assaf Our Jan 04 '17 at 09:59