从类型'System.String'到类型''X'的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换

MrB*_*liz 29 .net c# razor asp.net-mvc-3

我对这个感到困惑,你的帮助最有用.

我收到错误:

从类型'System.String'到类型'DataPortal.Models.EntityClasses.FeedbackComment'的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换

ModelState.IsValid是失败的FeedbackComment.Comment财产

有任何想法吗?

public class FeedbackComment : IFeedbackComment
{
    [Key]
    public int Id { get; set;}

    public int FeedbackId { get; set; }

     [Required(ErrorMessage = "Please enter a Comment")]
    public string Comment { get; set; }

    public DateTime CommentDate { get; set; }

    public string CommentBy { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器方法

//
    // GET: /FeedbackComment/Create

    public virtual ActionResult Create(int feedbackId)
    {
        var comment = new FeedbackComment {FeedbackId = feedbackId, CommentBy = User.Identity.Name, CommentDate = DateTime.Now};
        return View(comment);
    } 

    //
    // POST: /FeedbackComment/Create

    [HttpPost]
    public virtual ActionResult Create(FeedbackComment comment)
    {

        if (ModelState.IsValid)
        {

            _feedbackCommentRepository.Add(comment);

            return RedirectToAction(MVC.Feedback.Details(comment.FeedbackId));
        }

        return View(comment);
    }
Run Code Online (Sandbox Code Playgroud)

和观点

@model DataPortal.Models.EntityClasses.FeedbackComment
@{
ViewBag.Title = "Create Comment";
}
<h2>Create Comment</h2>
Run Code Online (Sandbox Code Playgroud)
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Feedback Comment</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Comment)
    </div>
    <div class="editor-field">
        @Html.TextAreaFor(model => model.Comment, new{@class = "TextEditor"})
        @Html.ValidationMessageFor(model => model.Comment)
    </div>


    @Html.HiddenFor(model=> model.CommentDate)
    @Html.HiddenFor(model=> model.CommentBy)       
    @Html.HiddenFor(model=> model.FeedbackId)

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to Comment Details", MVC.Feedback.Details(Model.FeedbackId))
</div>
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 78

问题是您的action参数的名称:

public virtual ActionResult Create(FeedbackComment comment)
Run Code Online (Sandbox Code Playgroud)

它被称为comment.但是你FeedbackComment也有一个名为Commentstring类型的属性.所以默认的模型绑定器变得疯狂.只需重命名其中一个以避免冲突.

例如,以下内容将解决您的问题:

public virtual ActionResult Create(FeedbackComment model)
{
    if (ModelState.IsValid)
    {
        _feedbackCommentRepository.Add(model);
        return RedirectToAction(MVC.Feedback.Details(model.FeedbackId));
    }
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)