简体   繁体   中英

Return type 'System.String' is not supported. Parameter name: expression MVC Enum

I am trying to create dropdown list from Enum in Asp.net MVC. With the below posted code, I am getting above error.

Here is code:

<div class="col-md-10">
            @Html.EnumDropDownListFor(model => model.SenderType, null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.SenderType, "", new { @class = "text-danger" })
        </div>

My controller:

public ActionResult Create([Bind(Include = "SenderId,SenderName,SenderType,SenderPurpose,UserId")] SenderModel senderModel)
    {
        try
        {

            if (ModelState.IsValid)
            {
                var currentUserId = User.Identity.GetUserId();
                senderModel.UserId = int.Parse(currentUserId);

                db.Sender.Add(senderModel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (DataException /* dex */)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        return View(senderModel);
    }

Model:

public enum SenderType
{
    Transactional,
    Promotional
}
public class SenderModel
{
    [Key]
    public int SenderId { get; set; }

    [Display(Name = "Sender Name")]
    public string SenderName { get; set; }
    [Display(Name = "Sender Type")]
    public string SenderType { get; set; }
    [Display(Name = "Sender Purpose")]
    public string SenderPurpose { get; set;}

    public int UserId { get; set; }
    public virtual ApplicationUser User { get; set; }
}

I have posted my code. Help would be appreciated

As you have SenderType property as string type in your model which has been used in your razor, which is not supported by EnumDropDownListFor . EnumDropDownListFor expect enum type property so your SenderType property should be of type SenderType enum. So, your model should be :

public class SenderModel
{
    [Key]
    public int SenderId { get; set; }

    [Display(Name = "Sender Name")]
    public string SenderName { get; set; }

    [Display(Name = "Sender Type")]
    public SenderType SenderType { get; set; } // SenderType should be of type enum SenderType
    [Display(Name = "Sender Purpose")]
    public string SenderPurpose { get; set;}

    public int UserId { get; set; }
    public virtual ApplicationUser User { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM