简体   繁体   中英

Why does clicking @Url.Action throws an error?

When I click a button input which triggers an action ImagePopup inside a controller Stories but it throws an error.

Code:

@{
    var listData = (List<HimHer.Models.Stories>)ViewBag.Grid;

    foreach (var imageName in listData)
    {
        <div class="col-md-4">
            @Html.HiddenFor(model => model.Story)          
            <input
                class="img-responsive img-thumbnail"
                type="image"
                onclick="location.href='@Url.Action("ImagePopup", "Stories", new {story= imageName.Story})'"
                src="@("/UploadedFiles/"+ imageName.Image)"
                alt="Submit"
                width="100%"
                height="100%"/>
        </div>
    }
}

Upon clicking an input it throws an error:

The resource cannot be found. Requested URL: /Stories/ImagePopup

Even though it exists. It is right inside the Stories folder. It's a partial view without a model.

[HttpPost]
public ActionResult ImagePopup(string story)
{            
    ViewBag.PopupStyle = "";
    ViewBag.PopupStory = story;
    return View("GetImagesStories");
}

What am I doing wrong?

It's looking for an HTTPGet Action I believe. If you want to call your post, you'll need to use HTML.BeginForm but it can get hairy if there are too many on a page.

尝试对您的ImagePopup操作方法使用[HttpGet]属性

Setting the href location of the current page:

location.href=

Causes the browser to do a Get Request type and does not post any form data back to your controller. Because the method on your controller specifically only works for post requests (because of the [HttpPost] attribute) there is no other matching methods that could work, thus you get an Exception.

Solutions:

You can continue using the Get method. Replace [HttpPost] with [HttpGet] will get you half way there. The other requirement will be for you to make sure the Url.Action code contains all the necessary information to be posted back (for example all the data in @Html.HiddenFor(model => model.Story) is not included, I don't know if you need it or not).

Or

You can modify your code to use the Post method. Change your <input type="image" to a <button type="submit"> and add a form around each button and hidden input element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM