1

I am working on a search page which displays a table of results. I want to add some functionality with Javascript. The entire table is encapsulated within a form, and each item on the table has several actions you can perform; One example is Add comment.

I am able to pass all the other form variables correctly as they are static. The issue I am having is being able to pass the ID to the action since it changes for each row of the result. Here is what I have so far (shortened)

Action header:

public ActionResult Create( ........., Int ID);

View:

...

@foreach( var item in Model )
{
    ...
    @Html.ActionLink("Comment", "Create", "Comment", new { ID = Model.ID }, new { onclick = "CommentSubmit(@Model.ID)" })
}

Javascript:

function CommentSubmit(id) {

            //What do?
    $("#DynForm").attr("action", "/Comment/Create");
    $("#DynForm").submit();
};

How can I just Javascript/jQuery to pass in the ID in addition to my other form variables?

Kind of a side question, but do I need stop the original anchor from executing (since my javascript is submitting the form)? How do I do this?

2 Answers 2

1

You can create or update an hidden input before submitting your form with the id

function CommentSubmit(id) {
    if($("#DynForm #id").length > 0)
        $("#DynForm #id").val(id);
    else
        $("#DynForm").append("<input type='hidden' id='id' name='id' value='"+id+"' />");

    $("#DynForm").attr("action", "/Comment/Create");
    $("#DynForm").submit();
};
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, so it's that easy... Thanks
1

you could do this

<input type="hidden" name="myID" />


function CommentSubmit(id) {

    $("#myID").val(id);        
    $("#DynForm").attr("action", "/Comment/Create");
    $("#DynForm").submit();
};

then in controller just add myID as a parameter

Public ActionResult Action(string myID , .... ){

}

or , you could just do this

 function CommentSubmit(id) {
        //What do?
$("#DynForm").attr("action", "/Comment/Create/" + id);
$("#DynForm").submit();

};

the default routing in Asp.Net will use the third part of url as parameter "id"

ex. {controller}/{action}/{id}

Comments

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.