官术网_书友最值得收藏!

Creating controller action

The changes we made in the previous section need to be updated in the SelectList collection, which will be used by MVC to render the drop-down list. By default, MVC scaffolding provides a SelectList (we have commented on that line) that has Id in the Value field and needs to be modified to Url, otherwise it will display only numeric values on the screen (a serious security issue and not so user-friendly):

    public IActionResult Create()
{
//ViewData["BlogId"] = new SelectList(_context.Blog, "Id", "Id");
ViewData["BlogId"] = new SelectList(_context.Blog, "Id", "Url");
return View();
}

The following screenshot shows the Url mapped to the BlogId control, but there is something additional that needs to be fixed. The BlogId should be either just Blog or Blog URL.

I will leave this part as an exercise, kindly make changes to all the labels associated with the BlogId column:

Posts create view

The same change needs to be applied to the Post action of Create as well:

    [HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult>
Create([
Bind("Id,BlogId,Content,PublishedDateTime,Title")]
Post post)
{
...
ViewData["BlogId"] = new SelectList(_context.Blog, "Id", "Url",
post.BlogId);
return View(post);
}

The changes are reflected in the newly included/added items displayed on the screen (the Index action was already modified to list the Blog URLs):

List view with new post

We have updated the references to the Blog ID with Blog URLs in the Post Create (HTTP, GET, and POST) action. Let's update the same on the other actions as well.

主站蜘蛛池模板: 玛多县| 和硕县| 雅安市| 五莲县| 香港| 洱源县| 鄄城县| 新丰县| 玉林市| 年辖:市辖区| 泽州县| 如皋市| 津市市| 嘉善县| 瓦房店市| 莲花县| 金坛市| 岑巩县| 隆子县| 怀来县| 永清县| 平塘县| 嵊泗县| 西乌珠穆沁旗| 高州市| 漠河县| 永昌县| 利川市| 稷山县| 攀枝花市| 东阿县| 壶关县| 东山县| 辽阳市| 独山县| 闻喜县| 溆浦县| 华池县| 东阳市| 五华县| 江城|