2

Grrr I'm having a ton of problems with this. Hope someone can help here. BEFORE you answer please keep in mind I have searched already and found plenty of topics already about this.

At the moment, I am attempting to populate an HTML form using a typical POST request (first time doing this, I am normally a very good programmer, but this web service stuff in ASP .NET Web API is killing me because of the odd idiosyncracies.) My drop down list should contain the below enumeration as values to choose from:

public enum FuelTypes
{
    Gasoline = 0,
    Diesel = 1
};

YES I have made sure to pass in my model instance when calling View in my controller.

The line that keeps breaking in "Debug" mode is in the HTML right here (You can see I commented it out for clarity below.):

@Html.DropDownListFor(model => model.FuelId, Model.FuelTypesList, "--Fuel Type--")

So there must be something else that's wrong this time. Please take a look at my relevant code below written in C# and HTML respectively:

P.S. Any other hints to improve what I already have would be GREAT! I am quite new to this. But I need to be able to get those drop down values to populate and display. Then I must create relevant objects from my HttpWrapper object containing all the data being POSTed.

Thanks in advance!

My Model:

public class FuelModel
{
    public FuelModel()
    {
        FuelTypesList = new List<SelectListItem>();
    }
    [Display(Name = "FuelType")]
    public int FuelId
    {
        get; set;
    }
    public IEnumerable<SelectListItem> FuelTypesList
    {
        get; set;
    }
}

My Controller:

public class ActionController : Controller
{
    // POST: Action
    [HttpPost]
    [ActionName("FuelType")]
    public ActionResult Index(FuelModel Model)
    {
        Model = new FuelModel();

        // This is where the "FuelType" Enum is referenced to access values 
        later from the HTML form.
        IEnumerable<FuelTypes> FuelType = 
        Enum.GetValues(typeof(FuelTypes)).Cast<FuelTypes>();
        Model.FuelTypesList = 
        from action in FuelType
        select new SelectListItem
        {
            Text = action.ToString(),
            Value = ((int)action).ToString()
        };

        return View(Model);
    }
}

My View (Containing HTML/JavaScript):

<div id="body">
    <ul id="caradvertisements"></ul>
</div>

<form id="saveCarAdvertisementForm" method="POST">
    <h3>Create A New Car Advertisement</h3>
    <p>
        <label for="New">New or Used:</label>
        <div align="left">
            <select name="mydropdown">
                <option value="New">New</option>
                <option value="Used">Used</option>
            </select>
        </div>
    </p>
    <p>
        <label for="Id">Car Id:</label>
        <input type="text" name="Id" />
    </p>
    <p>
        <label for="Title">Car Title:</label>
        <input type="text" name="Title" />
    </p>
    <p>
        @model AutoWebService.Models.FuelModel
        @{
            ViewBag.Title = "Index";
        }
        @Html.LabelFor(model => model.FuelId)
        @Html.DropDownListFor(model => model.FuelId, Model.FuelTypesList)
        @Html.DropDownListFor(model => model.FuelId, Model.FuelTypesList, "--Fuel Type--")

         <div align="left">
            <label for="Fuel">Car Fuel Type:</label>
            <select name="mydropdown">
                <option value="Gasoline">Gasoline</option>
                <option value="Diesel">Diesel</option>
            </select>
        </div>
    </p>
    <p>
        <label for="Price">Car Price:</label>
        <input type="text" name="Price" />
    </p>
    <input type="button" id="saveCarAdvertisement" value="Save" />
</form>

@section scripts{
<script type="text/javascript">
$(function()
{
    $.getJSON('/api/caradvertisement', function(caradvertisementsJsonPayload)
    {
        $(caradvertisementsJsonPayload).each(function (i, item)
        {
            $('#caradvertisements').append('<li>' + item.Name + '</li>');
        });
    });
});
$('#saveCarAdvertisement').click(function ()
{
    $.post("api/caradvertisement",
          $("#saveCarAdvertisementForm").serialize(),
          function (value)
          {
              $('#caradvertisements').append('<li>' + value.Name + '</li>');
          },
          "json"
    );
});
</script>
}
Brad
  • 21
  • 5
  • Can you explain in more detail, i checked your code. Nothing is rendering initially,i removed [HttpPost] attribute then form rendered. – Vijay Raheja Jun 27 '17 at 04:30
  • Hello, I get the following exception when I run everything in Visual Studio 2015: System.NullReferenceException was unhandled by user code HResult=-2147467261 Message=Object reference not set to an instance of an object. Source=App_Web_bkzznufe StackTrace: at ASP._Page_Views_Home_Index_cshtml.Execute() in c:\users\brad\documents\visual studio 2015\Projects\AutoScout24\AutoWebService\Views\Home\Index.cshtml:line 33 – Brad Jun 27 '17 at 04:35
  • can you share code code solution. – Vijay Raheja Jun 27 '17 at 04:49
  • Yes, of course. How can I send it to you? – Brad Jun 27 '17 at 05:24
  • via posting code files here – Vijay Raheja Jun 27 '17 at 05:48

1 Answers1

1

I believe you have found a solution to your problem.

Otherwise this is a working solution

Html.DropDownListFor(o => o.EnumProperty, Enum.GetValues(typeof(enumtype)).Cast<enumtype>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))

Found it here https://stackoverflow.com/a/2416623/7349807

FRANCISCO KK
  • 573
  • 1
  • 11
  • 18