Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C“为什么不能在使用“时转换System.String”;DropDownListFor";?_C#_Asp.net Mvc_Html.dropdownlistfor_Selectlistitem - Fatal编程技术网

C# C“为什么不能在使用“时转换System.String”;DropDownListFor";?

C# C“为什么不能在使用“时转换System.String”;DropDownListFor";?,c#,asp.net-mvc,html.dropdownlistfor,selectlistitem,C#,Asp.net Mvc,Html.dropdownlistfor,Selectlistitem,首先,我的观点是创建一个项目。用户将能够从dropdownlist中选择此项目的父项目。当用户选择项目的父项目时,应将其作为父项目属性保存到数据库(db) 我的错误信息如下 [System.InvalidOperationException]={“从类型'System.String'到类型'ProjectName.Models.Project'的参数转换失败,因为没有类型转换器可以在这些类型之间转换。”} 我的项目控制器操作: //GET public ActionResult

首先,我的观点是创建一个项目。用户将能够从dropdownlist中选择此项目的父项目。当用户选择项目的父项目时,应将其作为父项目属性保存到数据库(db)

我的错误信息如下

[System.InvalidOperationException]={“从类型'System.String'到类型'ProjectName.Models.Project'的参数转换失败,因为没有类型转换器可以在这些类型之间转换。”}

我的项目控制器操作:

    //GET
    public ActionResult Create()
    {

        var projectList = db.Projects.ToList().Select(
            c => new SelectListItem
                {
                    Selected = false,
                    Text = c.projectName,
                    Value = c.projectID.ToString()
                }
            ).ToList();
        ViewData["ProjectList"] = projectList;
        return View();
    }

    //
    // POST: /Project/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Project project)
    {
        var projectList = db.Projects.ToList().Select(
            c => new SelectListItem
                {
                    Selected = false,
                    Text = c.projectName,
                    Value = c.projectID.ToString()
                }
            ).ToList();
        ViewData["ProjectList"] = projectList;

        if (ModelState.IsValid)
        {
            db.Projects.Add(project);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(project);
    }
我的专题课:

 public class Project{

    public int projectID { get; set; }


    public string projectName { get; set; }


    public string descriptionProject { get; set; }

    public Project parentProject { get; set; }
 }
我的上下文类:

public class DBContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Project> Projects { get; set; }
    public DbSet<Issue> Issues { get; set; }
}
公共类DBContext:DBContext
{
公共数据库集用户{get;set;}
公共数据库集项目{get;set;}
公共数据库集问题{get;set;}
}
最后,我的观点是:

        @model ProjectName.Models.Project
        ....

        <div class="form-group">
            @Html.LabelFor(model => model.parentProject, new { @class = "col-lg-2 control-label" })

            <div class="col-lg-10">
                <p>@Html.DropDownListFor(model => model.projectID, (IEnumerable<SelectListItem>)ViewData["ProjectList"], " --Select Parent Project--")</p>
                @Html.ValidationMessageFor(model => model.parentProject)
            </div>
        </div>
@model ProjectName.Models.Project
....
@LabelFor(model=>model.parentProject,新的{@class=“col-lg-2控制标签”})
@Html.DropDownListFor(model=>model.projectID,(IEnumerable)ViewData[“项目列表”],“--选择父项目--”)

@Html.ValidationMessageFor(model=>model.parentProject)

我在等待你的答复。提前谢谢。顺便说一下,我正在使用MVC5.2,VisualStudio2013更新2

在控制器中:将所选项目的列表添加到视图模型中,而不是添加viewBag或view数据,因为它们不是强类型的。这样做是一种很好的做法。不要在HtmlHelper中转换

顺便说一句,这里是我创建的一个通用方法,用于填充我的一个项目中的下拉列表。您甚至可以附加静态值,如全部或无

    public IEnumerable<SelectListItem> GetSelection<T>(IEnumerable<T> data,
       Func<T, string> name = null,
       Func<T, string> key = null,
       string defaultValue = "0",
       bool showAllValue = true,
       bool showNothing = false)
    {
        var selectItemList = new List<SelectListItem>();
        if (showAllValue)
        {
            selectItemList.Add(new SelectListItem { Text = "Choose All", Value = 0 });
        }
        if (showNothing)
        {
            selectItemList.Add(new SelectListItem { Text = "Nothing Selected", Value = -1 });
        }

        selectItemList.AddRange(data.Select(item => key != null ? (name != null ? new SelectListItem
        {
            Text = name(item),
            Value = key(item)
        } : null) : null));

        //default selection
        var defaultItem = selectItemList.FirstOrDefault(x => x.Value == defaultValue);
        if (defaultItem != null)
        {
            defaultItem.Selected = true;
        }
        else
        {
            var firstItem = selectItemList.FirstOrDefault();
            if (firstItem != null) firstItem.Selected = true;
        }
        return selectItemList;
    }
public IEnumerable GetSelection(IEnumerable数据,
Func name=null,
Func key=null,
字符串defaultValue=“0”,
bool showAllValue=true,
bool showNothing=false)
{
var selectItemList=新列表();
if(showAllValue)
{
添加(新的SelectListItem{Text=“Choose All”,Value=0});
}
如果(不显示任何内容)
{
添加(新的SelectListItem{Text=“Nothing Selected”,Value=-1});
}
selectItemList.AddRange(data.Select(item=>key!=null?(name!=null?新建SelectListItem
{
Text=名称(项目),
值=键(项)
}:null):null);
//默认选择
var defaultItem=selectItemList.FirstOrDefault(x=>x.Value==defaultValue);
if(defaultItem!=null)
{
defaultItem.Selected=true;
}
其他的
{
var firstItem=selectItemList.FirstOrDefault();
如果(firstItem!=null)firstItem.Selected=true;
}
返回selectItemList;
}
你可以这样称呼它:

public IEnumerable<SelectListItem> GetClientSelectionList(string defaultClient = "0", bool showAllValue = false)
    {
        return this.GetSelection(data: _clientsManager.GetClients(),
                                        name: s => s.Client_Name,
                                        key: s => s.Client_ID.ToString(CultureInfo.InvariantCulture),
                                        defaultValue: defaultClient,
                                        showAllValue: showAllValue
            );
    }
public IEnumerable GetClientSelectionList(字符串defaultClient=“0”,bool showAllValue=false) { 返回此.GetSelection(数据:_clientsManager.GetClients(), name:s=>s.Client\u name, key:s=>s.Client\u ID.ToString(CultureInfo.InvariantCulture), defaultValue:defaultClient, showAllValue:showAllValue ); }
在我的“创建”视图中,异常准确地抛出在哪里@Html.DropDownListFor(model=>model.projectID,(IEnumerable)ViewData[“ProjectList”],“--选择父项目--”)

就在这里,您的解决方案非常有用。它起作用了。非常感谢你。