How to pass values from view to controller in ASP.

2019-03-05 23:44发布

I have this table in database:

http://i.stack.imgur.com/C7CWX.png

And I display all value in 'music' without repitions by this code(View):

@foreach (var item in Model.Select(m => m.music).Distinct())
{
    <tr>
        <td>
            @Html.ActionLink(item, "Deep", ViewData["item"])
        </td>
    </tr>
}

Result:

Jazz
Disko
Rock
Metal

And I want when I pressed 'Jazz' result was 'Miles','Kirk' etc. How do it? I think I may pass value from View to Controller, but i dont know how do it in my situation. Please help me

Action in controller(for example):

    public ActionResult Deep(string music)
    {

        var res = (from m in d.table where m.music == music select m);
        return View(res);
    }

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-06 00:06

It isn't possible to pass values from view to controller directly. When user asks web server for you initial page web server (ASP.NET) figures out the action to invoke. That action gathers data and sends that data (using view models, ViewBag, ViewData or TempData) to the view for rendering. Rendering in this case is process where your data is transformed to HTML (can be anything really CSS, JavaScript,... look at this as array of bytes) which is send to the client (browser) which interpret it as web page. User sees your link and when he clicks on it he will make the new request to the web server and this process repeats.

You are creating the code for links with: @Html.ActionLink(item, "Deep", ViewData["item"])

First parameter item is link text. "Deep" is name of action to invoke on current controller. Third parameter is of type object. This third parameter should be the same type as the parameters in the Deep action and you should use next notation for passing data

@Html.ActionLink(item, "Deep", new { idItem = item.IdMusic, foo = "bar" })

In previous example ASP MVC expects that your "Deep" action has parameters idItem and foo.

One thing to note is that client/user is making a request to the web server, he cant send an object like you tried. Instead you send unique identifier (idMusic) of object and retrieve it upon request from database/cache/session.

Hope this helps, Zlatibor

查看更多
Anthone
3楼-- · 2019-03-06 00:23

your Actionlink isn't quite doing what you want. If you hover over the links generated I think each one will name a different controller!

http://msdn.microsoft.com/en-us/library/dd505070.aspx

instead look at this version

http://msdn.microsoft.com/en-us/library/dd493066.aspx

@Html.ActionLink(item, "Deep", "YourController", new {id= ViewData["item"]})

and a controller action like

public ActionResult Deep(int id)
{
  //Do something
}
查看更多
登录 后发表回答