SKale
SKale

Reputation: 571

Pass parameter to method from button click

I have an MVC view where a logged in user chooses a course (i have dropdown list) and clicks the add button. My controller gets the logged in person's ID and then does the add. I can't figure out how to pass the chosen courseId to my post method in the controller.

I have something like:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ChooseCoursePreferences()
    {
        ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "Name");
        int personid = repository.GetLoggedInPersonId();
        int courseid = ???;
        repository.AddCoursePreferences(personid, courseid);
        return View();
    }

The View has:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <table class="table">
        <tr>
            <td>PLease choose a course:</td>
            <td>@Html.DropDownList("CourseId", String.Empty)</td>
            @Html.ActionLink("Add", "ChooseCoursePreferences", new { ??? })
            <tr></tr>
    </table>
}

Also, what if I wanted to use a button as a click.

I tried this: but again how do I get my chosen courseId? Add Course

Thanks!

Upvotes: 0

Views: 309

Answers (2)

Zach Spencer
Zach Spencer

Reputation: 1889

I agree with revdrjrr completely, get familiar with the mvc, what you are doing is very basic. But I will help you out here.

//action results
[HttpGet]
public ActionResult ChooseCoursePreferences()
{
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChooseCoursePreferences(int CourseId)
{
    ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "Name");
    int personid = repository.GetLoggedInPersonId();
    int courseid = CourseId;
    repository.AddCoursePreferences(personid, courseid);
    return View();
}

View

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <table class="table">
       <tr>
            <td>PLease choose a course:</td>
            //i will need more information to be able to help you out here               
            //I am not quite sure where this information should come from
            <td>@Html.DropDownList("CourseId", String.Empty)</td>
            <input type="submit"/>
            <tr></tr>
    </table>
}

Upvotes: 1

revdrjrr
revdrjrr

Reputation: 1045

I think what you're asking is pretty basic. I would start by reading a couple tutorials. There's lots of background information that you'll find helpful. I recently learned .NET, and found the first few tutorials from Microsoft a great way to get started. http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started

Upvotes: 0

Related Questions