StrugglingCoder
StrugglingCoder

Reputation: 5011

How to pass an id from a razor view to a controller's action method in ASP .Net MVC?

So, here what bothers me with my first demo MVC Project . In my main view MyAction.cshtml , when you click on the Student UserName hyperlinks a partial view containing Student Details get rendered in the StudentDetails <div>.

Here is my main view :

@model IEnumerable<MvcApplication4.ViewModels.StudentViewModel>  
@{
    ViewBag.Title = "MyAction";
    Layout = "~/Views/Shared/_myTemplateLayoutPage.cshtml";
    }

<script>
    function RegisterClickHanders() {

        var url = '@Url.Action("DisplayClickedView","Private")'; 
        $('.editDetails').click(function () {
            var btnvalue = $('.editDetails').attr("value");
            var srchvalue = $(this).closest("tr").children().first().text();
            $('#Add_Update_Details').load(url, { searchText: btnvalue, searchValue: srchvalue });
        });
    }
</script>

<div id="content">
    <div id="mainpage">

    <h2>Registration Details</h2>
        <ul>
        @foreach(var item in Model) 
        {
            <li>
                @Ajax.ActionLink(item.UserName,
                "GetUserDetails", 
                new { id = item.Student.StudentId },
                    new AjaxOptions
                    {
                        UpdateTargetId = "StudentDetails",
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "GET",
                        OnComplete="RegisterClickHanders"
                    }
                )
            </li>
        }
        </ul>
        <div id ="StudentDetails"></div>
        <div id ="Add_Update_Details"></div>
    </div>

    <div id="sidebarbottom"></div>
</div>

And here is the partial view that gets rendered :

@model MvcApplication4.ViewModels.StudentViewModel

<h2>Student Details</h2>
<table border="1">
    <tr>
        <th>
            Name
        </th>
        <th>
            User Name
        </th>
        <th>
            Department
        </th>
        <th colspan="2">
            Actions
        </th>
    </tr>
    <tr>
        <td>
            @Html.DisplayFor(x => x.StudentFullName)
        </td>
        <td>
            @Html.DisplayFor(x => x.UserName)
        </td>
        <td>
            @Html.DisplayFor( x => x.DepartmentName)
        </td>
        <td>
            <input type="submit" class="editDetails" value="Edit Details" name="Command" />
        </td>
        <td>
            <input type="submit" class="addDetails" value="Add Details" name="Command" />
        </td>
    </tr>
</table>

Now the details that I show from the StudentViewModel contain StudentId too. Here is the StudentViewModel Class :

//View Model
public class StudentViewModel
{
    public Student Student { get; set; }

    public int StudentId { get; set; }

    [Display(Name = "StudentName")]
    [Required(ErrorMessage = "Student Name cannot be left blank")]
    public String StudentFullName
    {
        get
        {
            return String.Format("{0} {1}", Student.FirstName, Student.LastName);
        }
    }

    public String UserName { get; set; }

    [DataType(DataType.Password)]
    public String Password { get; set; }

    [DataType(DataType.Password)]
    [Compare("Password",ErrorMessage="Passwords do not match")]
    [Display(Name="Confirm Password")]
    public String C_Password { get; set; }

    [Display(Name = "Department Name")]
    public String DepartmentName { get; set; }

}

But I only show StudentFullName , UserName and DepartmentName in the view.

     [HttpGet]
    public PartialViewResult GetUserDetails(int? id)
    {
        StudentContext context = new StudentContext();

        var result = context.Students.Where(s => s.StudentId == id)
            .Include(s => s.Department)
            .Select(s => new StudentViewModel
                {
                    Student = s,
                    UserName = s.UserName,
                    DepartmentName = s.Department.DepartmentName
                }).First();

        return PartialView("_StudentDetails",result);

    }

But when click on the Edit Details button I want a view to be rendered for that record. What I am trying to do is :

   var url = '@Url.Action("DisplayClickedView","Private")'; 
        $('.editDetails').click(function () {
            var btnvalue = $('.editDetails').attr("value");
            var srchvalue = $(this).closest("tr").children().first().text();
            $('#Add_Update_Details').load(url, { searchText: btnvalue, searchValue: srchvalue });
        });

But this would get the StudentFullName in the srchvalue and based on that the partial view would be rendered. But I want it to be rendered based on the StudentId itself which is not there in the view.

enter image description here

How can I pass the StudentId to the action DisplayClickedView so that the update or edit happens based on the id itself ?

Upvotes: 4

Views: 4146

Answers (3)

user4103496
user4103496

Reputation:

Add the StudentID to your view model. Then you can add an href to your buttons via razor which includes the student id:

@model MvcApplication4.ViewModels.StudentViewModel

<h2>Student Details</h2>
<table border="1">
    <tr>
        <th>
            Name
        </th>
        <th>
            User Name
        </th>
        <th>
            Department
        </th>
        <th colspan="2">
            Actions
        </th>
    </tr>
    <tr>
        <td>
            @Html.DisplayFor(x => x.StudentFullName)
        </td>
        <td>
            @Html.DisplayFor(x => x.UserName)
        </td>
        <td>
            @Html.DisplayFor( x => x.DepartmentName)
        </td>
        <td>
            <a class="btn btn-default btn-sm" href="@Url.Content(~/Controller/Action")/@(x => x.StudentID)" type="submit">Edit</a>
        </td>
        <td>
            <a class="btn btn-default btn-sm" href="@Url.Content(~/Controller/Action")/@(x => x.StudentID)" type="submit">Add Details</a>
        </td>
    </tr>
</table>

Where controller and action are replaced with your controller and action.

Upvotes: 1

Thiago Ferreira
Thiago Ferreira

Reputation: 651

When I want to have some value inside a html property and access it in a javascript, i like to use the data-* attribute.

So, you can do something like this:

<input type="submit" class="editDetails" value="Edit Details" name="Command" data-student-id="@Model.StudentId"/>

And get it in your javascript:

var studentId = $('.editDetails').data("student-id");

This way you don't have to add a new "hidden" column inside your table neither change the default properties of your button.

Upvotes: 3

Pedro G. Dias
Pedro G. Dias

Reputation: 3222

<input type="hidden" name="id" value="@Model.Id" />

Upvotes: 0

Related Questions