Asp.net core mvc 在ASP.NET核心MVC视图中,如何访问当前模型的属性?

Asp.net core mvc 在ASP.NET核心MVC视图中,如何访问当前模型的属性?,asp.net-core-mvc,Asp.net Core Mvc,我正在ASP.NET核心MVC中制作一个基本的CRUD应用程序,允许用户与多个电视频道交互。当用户单击特定频道的“编辑”按钮时,将运行以下代码: <a asp-action="Edit" asp-route-id="@Html.Raw(channel.ID)">Edit</a> 编辑 接下来,用户将进入“编辑”视图。此视图包含具有每个可编辑属性的表单。以下是“描述”字段的示例: 此字段应包含现有描述,以便用户不必记住它是什么。如何将此信息从“索引”视图传递到此视图

我正在ASP.NET核心MVC中制作一个基本的CRUD应用程序,允许用户与多个电视频道交互。当用户单击特定频道的“编辑”按钮时,将运行以下代码:

<a asp-action="Edit" asp-route-id="@Html.Raw(channel.ID)">Edit</a>
编辑
接下来,用户将进入“编辑”视图。此视图包含具有每个可编辑属性的表单。以下是“描述”字段的示例:


此字段应包含现有描述,以便用户不必记住它是什么。如何将此信息从“索引”视图传递到此视图

编辑

根据请求,这是我的完整控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using TV_Channel_Manager.Models;
using System.Text.RegularExpressions;

namespace TV_Channel_Manager.Controllers
{
    public class ChannelController : Controller
    {
        // GET: Channel
        public async Task<ActionResult> Index()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:57412/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("Administrator:")));

                HttpResponseMessage response = await client.GetAsync("config/v1/project/channels");
                if (response.IsSuccessStatusCode)
                {
                    string responseStr = await response.Content.ReadAsStringAsync();
                    // change keys so that they match props, and convert to object
                    List<Channel> channels = JsonConvert.DeserializeObject<List<Channel>>(responseStr.Replace("PROJECT_ID", "ProjID").Replace("common.ALLTYPES_DESCRIPTION", "Desc").Replace("common.ALLTYPES_NAME", "Name").Replace("servermain.CHANNEL_DIAGNOSTICS_CAPTURE", "CaptureDiag").Replace("servermain.CHANNEL_NON_NORMALIZED_FLOATING_POINT_HANDLING", "NonNormalizedFloatHandling").Replace("servermain.CHANNEL_UNIQUE_ID", "ID").Replace("servermain.CHANNEL_WRITE_OPTIMIZATIONS_DUTY_CYCLE", "WriteOptimDutyCycle").Replace("servermain.CHANNEL_WRITE_OPTIMIZATIONS_METHOD", "WriteOptimMethod").Replace("servermain.MULTIPLE_TYPES_DEVICE_DRIVER", "Driver").Replace("simulator.CHANNEL_ITEM_PERSISTENCE", "ItemPersistence").Replace("simulator.CHANNEL_ITEM_PERSISTENCE_DATA_FILE", "ItemPersistenceFile"));
                ViewData["channels"] = channels; // pass object list to view
            }
        }

        return View();
    }

    // GET: Channel/Details/5
    public ActionResult Details(int id)
    {
        return View();
    }

    // GET: Channel/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Channel/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(IFormCollection collection)
    {
        try
        {
            // TODO: Add insert logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    // GET: Channel/Edit/5
    public ActionResult Edit(int id)
    {
        return View();
    }

    // POST: Channel/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit(long projID, string desc, string name, bool captureDiag, int nonNormalizedFloatHandling, long ID, int writeOptimDutyCycle, int writeOptimMethod, string driver, bool itemPersistence, string itemPersistenceFile)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:57412/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("Administrator:")));

            Channel newChannelObj = new Channel(projID, desc, name, captureDiag, nonNormalizedFloatHandling, ID, writeOptimDutyCycle, writeOptimMethod, driver, itemPersistence, itemPersistenceFile);
            // replace prop names with actual names
            string serialized = JsonConvert.SerializeObject(newChannelObj).Replace("\"ProjID\"", "\"PROJECT_ID\"").Replace("\"ID\"", "\"servermain.CHANNEL_UNIQUE_ID\"").Replace("Desc", "common.ALLTYPES_DESCRIPTION").Replace("Name", "common.ALLTYPES_NAME").Replace("CaptureDiag", "servermain.CHANNEL_DIAGNOSTICS_CAPTURE").Replace("NonNormalizedFloatHandling", "servermain.CHANNEL_NON_NORMALIZED_FLOATING_POINT_HANDLING").Replace("WriteOptimDutyCycle", "servermain.CHANNEL_WRITE_OPTIMIZATIONS_DUTY_CYCLE").Replace("WriteOptimMethod", "servermain.CHANNEL_WRITE_OPTIMIZATIONS_METHOD").Replace("Driver", "servermain.MULTIPLE_TYPES_DEVICE_DRIVER").Replace("\"ItemPersistence\"", "\"simulator.CHANNEL_ITEM_PERSISTENCE\"").Replace("\"ItemPersistenceFile\"", "\"simulator.CHANNEL_ITEM_PERSISTENCE_DATA_FILE\"");
            StringContent newChannel = new StringContent(serialized, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PutAsync("config/v1/project/channels/" + name, newChannel);

            if (response.IsSuccessStatusCode)
                return View();
        }

        return NotFound();
    }

    // GET: Channel/Delete/5
    public ActionResult Delete(int id)
    {
        return View();
    }

    // POST: Channel/Delete/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Delete(int id, IFormCollection collection)
    {
        try
        {
            // TODO: Add delete logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Http;
使用Microsoft.AspNetCore.Mvc;
使用System.Net.Http;
使用System.Net.Http.Header;
使用系统文本;
使用System.IO;
使用Newtonsoft.Json;
使用TV_Channel_Manager.Models;
使用System.Text.RegularExpressions;
命名空间TV\u频道\u管理器.Controllers
{
公共类ChannelController:控制器
{
//获取:频道
公共异步任务索引()
{
使用(var client=new HttpClient())
{
client.BaseAddress=新Uri(“http://localhost:57412/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
client.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValue(“基本”,Convert.ToBase64String(asciencecoding.ASCII.GetBytes(“管理员”));
httpresponsemessageresponse=wait client.GetAsync(“config/v1/project/channels”);
if(响应。IsSuccessStatusCode)
{
string responsest=wait response.Content.ReadAsStringAsync();
//更改关键点,使其与道具匹配,并转换为对象
List channels=JsonConvert.DeserializeObject(responseStr.Replace(“PROJECT\u ID”,“ProjID”).Replace(“common.ALLTYPES\u DESCRIPTION”,“Desc”).Replace(“common.ALLTYPES\u NAME”,“NAME”).Replace(“servermain.CHANNEL\u DIAGNOSTICS\u CAPTURE”,“CaptureDiag”).Replace(“servermain.CHANNEL\u非规范化的浮点处理”,“非规范化的浮点处理”).Replace”).Replace.Replace(“servermain.CHANNEL\u UNIQUE\u ID”、“ID”).Replace(“servermain.CHANNEL\u WRITE\u OPTIMIZATIONS\u DUTY CYCLE”、“WriteOptimDutyCycle”).Replace(“servermain.CHANNEL\u WRITE\u OPTIMIZATIONS\u METHOD”、“WriteOptimMethod”).Replace(“servermain.MULTIPLE\u type\u DEVICE\u DRIVER”、“DRIVER”).Replace(“模拟器.CHANNEL\u ITEM\u ITEM\u PERSISTENCE”、“itempistence”).Replace”)simulator.CHANNEL_ITEM_PERSISTENCE_DATA_FILE(“itempsistencefile”);
ViewData[“通道”]=通道;//将对象列表传递给视图
}
}
返回视图();
}
//获取:频道/详细信息/5
公共行动结果详细信息(int id)
{
返回视图();
}
//获取:频道/创建
公共操作结果创建()
{
返回视图();
}
//发布:频道/创建
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果创建(IFormCollection集合)
{
尝试
{
//TODO:在此处添加插入逻辑
返回操作(“索引”);
}
抓住
{
返回视图();
}
}
//获取:频道/编辑/5
公共操作结果编辑(int id)
{
返回视图();
}
//发布:频道/编辑/5
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务编辑(long projID、string desc、string name、bool captureDiag、int nonNormalizedFloatHandling、long ID、int writeOptimDutyCycle、int writeOptimMethod、字符串驱动程序、bool itemPersistence、string itemPersistenceFile)
{
使用(var client=new HttpClient())
{
client.BaseAddress=新Uri(“http://localhost:57412/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
client.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValue(“基本”,Convert.ToBase64String(asciencecoding.ASCII.GetBytes(“管理员”));
Channel newChannelObj=新通道(projID、desc、name、captureDiag、非规范化floathandling、ID、writeOptimDutyCycle、writeOptimMethod、driver、itemPersistence、itemPersistenceFile);
//用实际名称替换道具名称
string serialized=JsonConvert.SerializedObject(newChannelObj)。替换(“\'ProjID\”、“\'PROJECT\u ID\”)。替换(“\'ID\”、“\'servermain.CHANNEL\u UNIQUE\u ID\”)。替换(“Desc”、“common.ALLTYPES\u DESCRIPTION”)。替换(“Name”、“common.ALLTYPES\u Name”)。替换(“CaptureDiag”、“servermain.CHANNEL\u DIAGNOSTICS\u CAPTURE”)。替换(“NonNormalizedFloatHandling”servermain.CHANNEL\u非规范化\u浮点处理”).Replace(“WriteOptimDutyCycle”、“servermain.CHANNEL\u WRITE\u OPTIMIZATIONS\u DUTY\u CYCLE”).Replace(“WriteOptimMethod”、“servermain.CHANNEL\u WRITE\u OPTIMIZATIONS\u METHOD”).Replace(“Driver”、“servermain.MULTIPLE\u Type\u DEVICE\u Driver”).Replace(“ItemPersistence\”,“\“simulator.CHANNEL\u ITEM\u PERSISTENCE\”)。替换(“ItemPersistenceFile\”,“simulator.CHANNEL\u ITEM\u PERSISTENCE\u DATA\u FILE\”);
StringContent newChannel=新的StringContent(序列化,Encoding.UTF8,“应用程序/json”);
httpresponsemessageresponse=wait client.PutAsync(“config/v1/project/channels/”+name,newChannel);
if(响应。IsSuccessStatusCode)
返回视图();
}
返回NotFound();
}
//获取:频道/删除/5
公共操作结果删除(int id)
{
返回视图();
}
//发布:频道/删除/5
[HttpPost]
[ValidateAntiForgeryToken]
公众的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using TV_Channel_Manager.Models;
using System.Text.RegularExpressions;

namespace TV_Channel_Manager.Controllers
{
    public class ChannelController : Controller
    {
        // GET: Channel
        public async Task<ActionResult> Index()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:57412/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("Administrator:")));

                HttpResponseMessage response = await client.GetAsync("config/v1/project/channels");
                if (response.IsSuccessStatusCode)
                {
                    string responseStr = await response.Content.ReadAsStringAsync();
                    // change keys so that they match props, and convert to object
                    List<Channel> channels = JsonConvert.DeserializeObject<List<Channel>>(responseStr.Replace("PROJECT_ID", "ProjID").Replace("common.ALLTYPES_DESCRIPTION", "Desc").Replace("common.ALLTYPES_NAME", "Name").Replace("servermain.CHANNEL_DIAGNOSTICS_CAPTURE", "CaptureDiag").Replace("servermain.CHANNEL_NON_NORMALIZED_FLOATING_POINT_HANDLING", "NonNormalizedFloatHandling").Replace("servermain.CHANNEL_UNIQUE_ID", "ID").Replace("servermain.CHANNEL_WRITE_OPTIMIZATIONS_DUTY_CYCLE", "WriteOptimDutyCycle").Replace("servermain.CHANNEL_WRITE_OPTIMIZATIONS_METHOD", "WriteOptimMethod").Replace("servermain.MULTIPLE_TYPES_DEVICE_DRIVER", "Driver").Replace("simulator.CHANNEL_ITEM_PERSISTENCE", "ItemPersistence").Replace("simulator.CHANNEL_ITEM_PERSISTENCE_DATA_FILE", "ItemPersistenceFile"));
                ViewData["channels"] = channels; // pass object list to view
            }
        }

        return View();
    }

    // GET: Channel/Details/5
    public ActionResult Details(int id)
    {
        return View();
    }

    // GET: Channel/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Channel/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(IFormCollection collection)
    {
        try
        {
            // TODO: Add insert logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    // GET: Channel/Edit/5
    public ActionResult Edit(int id)
    {
        return View();
    }

    // POST: Channel/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit(long projID, string desc, string name, bool captureDiag, int nonNormalizedFloatHandling, long ID, int writeOptimDutyCycle, int writeOptimMethod, string driver, bool itemPersistence, string itemPersistenceFile)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:57412/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("Administrator:")));

            Channel newChannelObj = new Channel(projID, desc, name, captureDiag, nonNormalizedFloatHandling, ID, writeOptimDutyCycle, writeOptimMethod, driver, itemPersistence, itemPersistenceFile);
            // replace prop names with actual names
            string serialized = JsonConvert.SerializeObject(newChannelObj).Replace("\"ProjID\"", "\"PROJECT_ID\"").Replace("\"ID\"", "\"servermain.CHANNEL_UNIQUE_ID\"").Replace("Desc", "common.ALLTYPES_DESCRIPTION").Replace("Name", "common.ALLTYPES_NAME").Replace("CaptureDiag", "servermain.CHANNEL_DIAGNOSTICS_CAPTURE").Replace("NonNormalizedFloatHandling", "servermain.CHANNEL_NON_NORMALIZED_FLOATING_POINT_HANDLING").Replace("WriteOptimDutyCycle", "servermain.CHANNEL_WRITE_OPTIMIZATIONS_DUTY_CYCLE").Replace("WriteOptimMethod", "servermain.CHANNEL_WRITE_OPTIMIZATIONS_METHOD").Replace("Driver", "servermain.MULTIPLE_TYPES_DEVICE_DRIVER").Replace("\"ItemPersistence\"", "\"simulator.CHANNEL_ITEM_PERSISTENCE\"").Replace("\"ItemPersistenceFile\"", "\"simulator.CHANNEL_ITEM_PERSISTENCE_DATA_FILE\"");
            StringContent newChannel = new StringContent(serialized, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PutAsync("config/v1/project/channels/" + name, newChannel);

            if (response.IsSuccessStatusCode)
                return View();
        }

        return NotFound();
    }

    // GET: Channel/Delete/5
    public ActionResult Delete(int id)
    {
        return View();
    }

    // POST: Channel/Delete/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Delete(int id, IFormCollection collection)
    {
        try
        {
            // TODO: Add delete logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}
// GET: Channel/Edit/5
    public ActionResult Edit(long projID, string desc, string name, bool captureDiag, int nonNormalizedFloatHandling, long id, int writeOptimDutyCycle, int writeOptimMethod, string driver, bool itemPersistence, string itemPersistenceFile)
    {
        ViewData["projID"] = projID;
        ViewData["desc"] = desc;
        ViewData["name"] = name;
        ViewData["captureDiag"] = captureDiag;
        ViewData["nonNormalizedFloatHandling"] = nonNormalizedFloatHandling;
        ViewData["id"] = id;
        ViewData["writeOptimDutyCycle"] = writeOptimDutyCycle;
        ViewData["writeOptimMethod"] = writeOptimMethod;
        ViewData["driver"] = driver;
        ViewData["itemPersistence"] = itemPersistence;
        ViewData["itemPersistenceFile"] = itemPersistenceFile;

        return View();
    }
<a asp-action="Edit" asp-controller="Channel" asp-route-projid="@Html.Raw(channel.ProjID)" asp-route-desc="@Html.Raw(channel.Desc)" asp-route-name="@Html.Raw(channel.Name)" asp-route-capturediag="@Html.Raw(channel.CaptureDiag)" asp-route-nonnormalizedfloathandling="@Html.Raw(channel.NonNormalizedFloatHandling)" asp-route-id="@Html.Raw(channel.ID)" asp-route-writeoptimdutycycle="@Html.Raw(channel.WriteOptimDutyCycle)" asp-route-writeoptimmethod="@Html.Raw(channel.WriteOptimMethod)" asp-route-driver="@Html.Raw(channel.Driver)" asp-route-itempersistence="@Html.Raw(channel.ItemPersistence)" asp-route-itempersistencefile="@Html.Raw(channel.ItemPersistenceFile)">Edit</a> |
return View(model);
@model YourModelType