简体   繁体   中英

How to pass enum value to controller with ajax?

I want to pass my enum value to controller.

I have this enum in my model:

public enum Section
{
      Upper,
      Lower
};

I want to pass this value through ajax on my controller:

$(function () {
  var section='@Section.Upper'//i want to pass Upper value only to my controller.
  alert(section) ///output Upper
 $.ajax({
                url: '/Section/FindSection',
                data: { 'Section': section},
 });

In Database table it is storing 1 for upper and 0 for lower.

My Controller:

public ActionResult Generate(int FindSection)
{   
}

Error:The parameters dictionary contains a null entry for parameter 'FindSection' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Generate(Int32)'

I know i can pass directly pass 1 but i dont want to hardcode because in future if i need to pass any other thing then again i have to change the code.

how can i do this???

You just need to pass the index of the item you want.

public ActionResult Generate(Section section)
{   

}

$(function () {
  //...
 $.ajax({
            url: '/Section/Generate',
            data: { section: 1} //the controller will receive Super.Lower
 });
 //..
})

Change the action code to:

public ActionResult Generate(Section Section) {  }

Also do not use hardcoded urls in ASP.NET MVC, utilize url helpers instead:

$.ajax({
    url: '@Url.Action("Generate", "Section")',
    data: { 'Section': section }
 });

Edit: If changing the method parameter is not an option, than use the correct name in the ajax method:

$.ajax({
    url: '@Url.Action("Generate", "Section")',
    data: { 'FindSection': section }
 });

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