Question

I'm very new with MVC, so please bear with my obvious questions

I created a simple MVC2 website in VS2010

I added a controlled in the controller folder Controller code:

namespace MVC2TestApp.Controllers
{
    using MVC2TestApp.Models;
    public class PeopleController : Controller
    {
        //
        // GET: /People/

        public ActionResult Index()
        {
            return View();
        }
      //  [HttpPost]
        public ActionResult AddPeople(PeopleModel person)
        {
            return View("Index");
        }
        [HttpPost]
        public ActionResult Add(PeopleModel person)
        {
            return View("Index");
        }
    }
}

View Code:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Index</h2>
    <button id="btnTest">Test</button>
    <script type="text/javascript">
        $(document).ready(function () {
            alert('ready got executed');
            $('#btnTest').click(function () {
               // debugger;
                try {
                    var person = { FirstName: "Joe", LastName: "Soap", Email: "a@b.c" };

                    alert(1);
                    $.ajax({
                        url: 'Add',
                        dataType: 'json',
                        data: person,
                        type: 'POST',
                        success: function (result) {
                            alert('step 3');
                            alert(result);
                        },
                        failure: function (result) {
                            alert('step 4');
                            alert(result);
                        }
                    });
                } catch (e) {
                    alert(e.responseText);
                } 

            });
        });
    </script>
</asp:Content>

People Controller:

namespace MVC2TestApp.Models
{
    public class PeopleModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email{get;set;}
    }
}

I set People page as my start up page by setting it up in properties of solution-->Web-->Start Action->Specific Page : People\

This works just as expected, I get the object in controller.

But when the startup page is set as Home, the code doesn't hit the controller. I don't know what I am doing wrong.

I tried changing the RegisterRoutes method in Global.asax. But that didn't help.

Global.asax code

namespace MVC2TestApp
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },// Parameter defaults
                new string[] { "MVC2TestApp.Controllers" }//This code was added to try to fix the problem
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }
    }
}

It's an MVC2 application. I have VS2010 Professional edition.

Was it helpful?

Solution

You could reference the full path to your action in your js.

You can get the full path by using this method (http://localhost:50000/People/Add):

@Url.Action("Add", "People", null, Request.Url.Scheme, null)

Then it will not matter which page you are on, you will always be able to call the same action, and no hassle with relative urls.

Sample:

      $('#btnTest').click(function () {
           // debugger;
            try {
                var person = { FirstName: "Joe", LastName: "Soap", Email: "a@b.c" };
                var url = '@Url.Action("Add", "People", null, Request.Url.Scheme, null)';
                alert("Url: " + url);
                $.ajax({
                    url: url,
                    dataType: 'json',
                    data: person,
                    type: 'POST',
                    success: function (result) {
                        alert("Success!");
                        alert(result);
                    },
                    failure: function (result) {
                        alert("Fail!");
                        alert(result);
                    }
                });
            } catch (e) {
                alert(e.responseText);
            } 

        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top