views:

64

answers:

2

I have following URL:

http://localhost:49970/Messages/Index/9999

And at view "Index" I have a form and I post the form data to the action Index (decored with [HttpPost]) using Jquery, like this:

View:

<script type="text/javascript">
    function getMessages() {
        var URL = "Index";
        $.post(
            URL,
            $("form").serialize(),
             function(data) {
                 $('#tabela').html(data);
             }
        );
    }
</script>

 <% using (Html.BeginForm()) {%>

        <%=Html.TextArea("Message") %>

        <input type="button" id="submit" value="Send" onclick="javascript:getMessages();" />

    <% } %>

Controller:

[HttpPost]
public ActionResult Index(FormCollection collection)
{
   //do something...
     return PartialView("SomePartialView", someModel);
}

My question: How can I get the parameter "9999" and the form FormCollection in the action Index?

PS: Sorry about my english :)

A: 

You need to declare the id in the routes collection. Then, just put a verible with the same name in the action.

public ActionResult Index(int id, string otherPostData...)
{
   //do something...
     return PartialView("SomePartialView", someModel);
}

Look here for the details how MVC url routing works:

http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

Mendy
Thanks for the fast answer Mendy :)Actually, my parameter is a guid (something like "08254a2a-7089-46e6-b03d-406a72a34148"). I try to declared the method like did you say:public ActionResult Index(Guid? id, string Message){ //id is null //Message is ok (has the value that I typed) return PartialView("SomePartialView", someModel);}If I change the nullable Guid? to only Guid, when I clck in the button nothing happens...
Fabio
A: 

A simple way would be to add the Id to your form values.

This should do the trick:

<% using (Html.BeginForm()) {%>

    <%=Html.Hidden("Id") %>

    <%=Html.TextArea("Message") %>

    <input type="button" id="submit" value="Send" onclick="javascript:getMessages();" />

<% } %>

If that doesn't work, you'll need to throw the Id into your ViewData in the controller.

Another way to do it (which could be cleaner) would be to get the URL that jQuery posts to from the form's action attribute. While you're at it I'd make the js unobtrusive too.

HTHs,
Charles

Charlino