简体   繁体   中英

returning data not in model to mvc controller

I have a field on my view (a checkbox) that has the value of an id from the model. I need to return a list of those ids that the user checked on the form to the controler action.

Every thing I have tried doesn't work. I have the view coded to return to the controller but I haven't figured out how to return the values needed.

This is a snippet of the checkbox in the view...

<td @trFormat >
    <input id="ExportCheck" type="checkbox" value = "@item.PernrId" onclick="saveid(value);"/>
</td>

currently the onclick event is firing a javascript on the view that should be storing the id values...

<script type="text/javascript">
    var keys = null;
    function saveid(id) {
        keys += id;
    }
</script>  

I have been trying to use an action call to get back to the controller. Currently there is no routing object being sent back because I can't figure out how to load it...

<input type="submit" value="Export to Excel" onclick="location.href='@Url.Action("ExportExcel","CastIndex")'" />

I know I am probably doing many things wrong with this code. I am just now working on my first MVC application. Any help would be appreciated. Ultimate outcome is that I need to have the ids in the controller to retrieve the selected ids and send them to an export to excel.

You could use a strongly typed model that looks like:

public class Item
{
    public int Id { get; set; }
    public string Name { get; set;}

    //Other properties...

    public bool Export {get; set;} //for tracking checked/unchecked
}

In your controller's GET action, build a List and pass that to a strongly typed view.

[HttpGet]
public ActionResult MyAction()
{ 
   var model = new List<Item>();

   //ToDo: Get your items and add them to the list... Possibly with model.add(item)

   return View(model);
}

In the view you can use the HTML helper "CheckBoxFor" to add a check box item for each item in the list.

@using (Html.BeginForm())
{

//other form elements here

@Html.CheckBoxFor(model=>model.Export) //this add the check boxes for each item in the model

<input type="submit" value="Submit" />

}

Your controller's POST action can consume the List and look for those with Export == true:

[HttpPost]
public ActionResult MyAction (List<Item> items)
{
  foreach(Item i in Items)
  {
     if(i.Export)
     {
         //do your thing...
     }
  }

  //Return or redirect - possibly to success action screen, or Index action.
}

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