0

I have an ASP.NET MVC page with multiple partial sections. Each of these sections has a script initialization and each be refreshed as a partial from itself.

<script type="text/javascript">
    $(document).ready(function () {
        var section1Config = {
            AddEditSection1Url: "@Url.Action("AddEditSection1", "Loan")"
        };
    });
</script>

On initial load, this renders like so:

<script type="text/javascript">
    $(document).ready(function () {
        var section1Config = {
            AddEditSection1Url: "/Loan/AddEditSection1"
        };
    });
</script>

When I refresh that partial section, the Url.Action includes the id that I passed in through AJAX without me asking it to:

<script type="text/javascript">
    $(document).ready(function () {
        var section1Config = {
            AddEditSection1Url: "/Loan/AddEditSection1/2"
        };
    });
</script>

Here's the call on the client side I'm making:

$.post('/Loan/AddEditSection1/2', function (data) {
    $('#loanadd-1').html(data);
});

And here's the server side code that's called by that jQuery post:

public PartialViewResult AddEditSection1(int id)
{
    var viewModel = GetPopulatedAddEditViewModel(id);
    return PartialView("Partials/AddEditSection1", viewModel);
}

Any clue as to why the render engine is being so "helpful"? It's really making things unnecessarily difficult.

  • any reason you do not just remove @Url.Action and hard code the URL? – Daveo Dec 29 '11 at 23:53
  • @Daveo You should avoid hardcoding URLs in MVC wherever possible – Chao Dec 30 '11 at 12:17
  • @Chao Why? My code "/Loan/AddEditSection1" is so much more readable and less platform dependant. If I want to swap my server side code to anther technology I do not have to rewrite my JavaScript. What benifit does using Url.Action give other then making it harder to read – Daveo Dec 30 '11 at 22:34

1 Answers1

1

A lot of the time you will actually find this behaviour quite useful, in fact you're used to it already, notice that often you will call Url.Action or Html.Action without your contrller name, it's all part of the same parameter provider.

Anyway, in situations where you explicitly don't want to include a parameter just pass in an object and set it to nothing:

<script type="text/javascript">
$(document).ready(function () {
    var section1Config = {
        AddEditSection1Url: "@Url.Action("AddEditSection1", "Loan", new {id=""})"
    };
});
</script>
Chao
  • 3,033
  • 3
  • 30
  • 36
  • To a degree that makes sense, but it doesn't explain why that gets appended ONLY to that Url.Action and not to the others I'm setting up. I left the others out for clarification, but they don't end up working the same way. For instance, AddLoanProfileAmortizationUrl: "@Url.Action("AddLoanProfileAmortization")" Renders the same way every time. Why does it work differently in the other case? – Nathanael Schulte Dec 30 '11 at 17:16