2

I have a drop down list that, when changed, should refresh the model for the view. Here is the controller:

    public ActionResult Index()
    {
       //do something totally awesome
    }

    [HttpPost]
    public ActionResult Index(int user)
    {
        //do something even more awesome with the new value selected from the drop down list 
    }

The relevant part of the View:

<div id="selectuser" class="user-input">@Html.DropDownListFor(x => x.SelectedUser, Model.Users)</div>

and the jQuery to handle the drop down list changing:

$(function () {
    $('#selectuser select').change(function () {
        $.post('@Url.Action("Index", "Home")', { user: $(this).val() }, function (result) {

        });
    });
});

It appears that everything is working, except the jQuery part. Evidently, the UrlAction(...) isn't right. When a user changes the selection, this is the URL MVC tries to load: http://localhost:5555/@Url.Action%28%22Index%22,%20%22Home%22%29

I was expecting MVC to route to the HttpPost Index action in the controller when a selection changed. Why didn't it? How do I fix it?

I'm a total noob at this - your help is greatly appreciated.

2 Answers 2

2

What's happening here is that the Razor engine isn't evaluating @Url.Action(). If I had to guess, I'd say that whatever is generating the JavaScript code isn't in the same razor view. If you haven't already, I'd start by moving the code into a block on the view page, if you haven't already. It's not clear from the original post whether the JQuery code is in the view or not.

Sign up to request clarification or add additional context in comments.

2 Comments

That was it! Thank you. The script was in another file. After moving the script into a <script> tag in the view, it worked. I'm not sure why it matters where the JS lives, but evidently it does matter.
It matters because the Razor engine only sees files that are processed through a controller. So if you wrote an action that returned JavaScript, that would work - but if you just have a plain .js file the web server just sends that right onto the browser without any additional processing.
0

Have you tried using ajax to call back to the function?

$('#selectuser select').change(function () {
   $.ajax({
       url: '@Url.Content("~/Home/Index")',
       type: "POST",
       data: val,
       datatype: "json",
       success: function (data, status, request) {
           // success code here
       },
       error: function (request, status, error) {
           // error code here
       }
    });
}

Here would be an example of a controller function (Index) that returns JSON:

[HttpPost]
public JsonResult Index(int val)
{
    try
    {
        // do what you need to here

        return Json(new
        {
             // Returning a partial view and success
             Html = this.RenderPartialView("_PartialView", model),
             Success = true
        });
    }
    catch (Exception ex)
    { 
        return Json(new
        {
             // Returning a partial view and and error
             Html = this.RenderPartialView("_PartialView", model),
             Success = false
        }, JsonRequestBehavior.AllowGet);
    }
}

I added some more examples below incase you must use an ActionResult and can't use a JsonResult.

http://blogs.us.sogeti.com/swilliams/2009/05/11/different-action-results-with-asp-net-mvc-and-jquery/

http://iridescence.no/post/Invoking-ASPNET-MVC-Actions-from-JavaScript-using-jQuery.aspx

Return ActionResult to a Dialog. ASP.NET MVC

4 Comments

Thanks for the response. I'm not sure how adding ajax would help. Alas, I tried using the script above and set a breakpoint in my existing controller that never gets hit. The error was basically the same (HTTP 500) because this is the URL it is trying to open: localhost:5555/@Url.Content%28%22~/Home/Index%22%29
I think you are missing something in your MVC 3 app. It should not come out like that. Try creating a new MVC 3 app and see if it still occurs.
Agreed with TIHan, there's no reason your url should look like that. Do you have all the necessary jquery references in your project? Have you put a breakpoint in your jQuery to see what exactly it's doing? Is your jQuery in the ready or pageLoad function?
Also, I'm confused why you're using the id of the div. You should try putting an id on your dropdownlist itself... such as : @Html.DropDownListFor(x => x.SelectedUser, Model.Users, new {id = "ddlUser"}) and use this as reference to grab your val and trigger your jquery

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.