ASP.NETMVC:没有为该对象定义的无参数构造函数?

  • 回答 (2)
  • 关注 (0)
  • 查看 (355)
Server Error in '/' Application.
--------------------------------------------------------------------------------

No parameterless constructor defined for this object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Source Error: 


Line 16:             HttpContext.Current.RewritePath(Request.ApplicationPath, false);
Line 17:             IHttpHandler httpHandler = new MvcHttpHandler();
Line 18:             httpHandler.ProcessRequest(HttpContext.Current);
Line 19:             HttpContext.Current.RewritePath(originalPath, false);
Line 20:         }

无法再加载自己的项目

济南庆典wtk济南庆典wtk提问于
liwen223回答于

如果模型使用的是SelectList:

public class MyViewModel
{
    public SelectList Contacts { get;set; }
}

需要重构模型才能做到这一点。所以使用IEnumerable<Contact>并编写一个扩展方法:

public class MyViewModel
{
    public Contact SelectedContact { get;set; }
    public IEnumerable<Contact> Contacts { get;set; }
}

public static MvcHtmlString DropDownListForContacts(this HtmlHelper helper, IEnumerable<Contact> contacts, string name, Contact selectedContact)
{
    // Create a List<SelectListItem>, populate it, return DropDownList(..)
}

或者可以使用@Mark和@krilovich方法,将SelectList替换为IEnDigable

 public class MyViewModel
    {
        public Contact SelectedContact { get;set; }
        public IEnumerable<SelectListItem> Contacts { get;set; }
    }
我是涛养猫爱好者回答于

以下是一个示例:

public class MyController : Controller
{
    public ActionResult Action(MyModel model)
    {

    }
}

public class MyModel
{
    public MyModel(IHelper helper) // MVC cannot call that
    {
        // ...
    }

    public MyModel() // MVC can call that
    {
    }
}

扫码关注云+社区

领取腾讯云代金券