简体   繁体   中英

Return table from viewmodel to controller in C# MVC

I have a view where I allow the user to add items to a table. The table gets built up using a simple html form and jquery to add new rows.

I need to be able to return the rows that are added from the view to the controller (ideally via a view model). Right now, all I can think of is to add the data in a delimited format to a hidden field using jquery.

However I worry about the length of the data being added may be too much for a hidden field, plus it's going to be complex to validate.

Any suggestions would be appreciated!

Thanks

May be using ready component will be more useful? As example Telerik or KendoUI can do it out of the box.

But if you want do it yourself, you could put this rows in javascript object and submit it with ajax request. In controller action it can be bound to modelview with help of modelbinder.

I guess it would be a litle bit more difficult using the view model since you have to know the number of fields you constantly expect to have although you might youse a list but not sure if it can be achived just with jquery but you can

increment the name of the input you create

<input type='text' name='somename1' />
<input type='text' name='somename2' />
<input type='text' name='somename3' />

and the on your backend

[HttpPost]
public ActionResult collect(FormCollection collection)
{
     List<string> names = Request.Params
    .Cast<string>()
    .Where(p => p.StartsWith("somename"))
    .ToList();
   //  then iterate thru your dynamically created controls
   foreach(var item in names)
   {
      string text=collection[item].ToString();

   } 
 }

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