开发者

Using MVC3, how do I set a TempData value when the user clicks on an HTML.ActionLink control?

I have a foreach loop that generates a table row for each item in an array of Business objects in the BusinessList view.

Here's my Business object:

    public class Business
    {
        public long BusinessID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

and here's the Razor foreach loop:

@foreach (var item in Model)
{
    <tr>
        <td>
            <div class="editor">
                <div class="editor-label">
                    @Html.DisplayFor(modelItem => item.Name)
                </div>
            </div>
        </td>
        <td>
            <div class="editor">
                <div class="editor-label">
                    @Html.DisplayFor(modelItem => item.Description)
                </div>
            </div>
        </td>
        <td>
            @Html.ActionLink("Edit", "EditBusiness")
        </td>
    </tr>
}

What I want to do is capture the BusinessID associated with the row in which the user clicks on the "Edit" button. The BusinessID value will need to be available to the EditBusiness view. I'd rather not use the querystring. Is there some way to set a Vi开发者_开发百科ewData, TempData, or ViewBag value when the user clicks the "Edit" link?


Rather than use pass the value as a querystring you could post the value by changing the edit link to a form with a hidden field for the ID and a submit button (styled like your edit link)

@using (Html.BeginForm("EditBusiness")) {
    @Html.HiddenFor(m => m.Id)
    <input type="submit" value="Edit" />
}

Or you could post via ajax.


There is no way to set the ViewData, TempData or ViewBag values on the client side (browser) because they are properties of a ASP.NET MVC view object on the server side. For what you need, you can use the ActionLink method like this:

@Html.ActionLink("Edit", "EditBusiness", new { Model.BusinessID })

This way, you will call the action http://<your_host>/Edit/EditBusiness/<BusinessId>


Change your "EditBusiness" action method to accept BusinessID parameter.

public ActionResult EditBusiness(string BusinessID )

and change your actionlink to this

@Html.ActionLink("Edit", "EditBusiness", new { BusinessID = Model.BusinessID })


First of all you should create an Action like this:

public ActionResult Edit(int id) {
    //....

  return View();
}

Then, on the View (.cshtml file) add the following:

@Html.ActionLink("Edit", "Business", new { id = Model.BusinessID })

Make sure method parameter name (Edit(int id)) is the same as "id = Model.BusinessID", which is "id".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜