Partial view renders as full view - asp.net-mvc-3

MVC 3 , ajax, c#
My partial view is rendering as a new page instead of replacing the search results table.
Controller:
public class SearchController : Controller
{
//
// GET: /Search/
private myEntities db = new myEntities();
private Repository repo = new Repository();
[HttpGet]
public ActionResult Index()
{
var model = new List<PersonViewModel>();
model = repo.GetPeople();
return View(model);
}
public PartialViewResult _SearchResult(string fname, string lname)
{
var personResult = repo.GetSearchResult(fname, lname);
return PartialView("_SearchResult", personResult);
}
}
The view:
<div class="page">
<div class="middle-col-comment-mod">
<h2>Search Existing Trespassers</h2>
<div id="search">
#using (Ajax.BeginForm("_SearchResult", "Search", null, new AjaxOptions { HttpMethod = "Post", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "indexSearchResults" }))
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
<input type="submit" name="submit" class="skbutton" value="Search" />
</div>
}
</div>
<table id="indexSearchResults" class="data-table">
<tr>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Gender
</th>
<th>
City
</th>
<th>
DOB
</th>
<th>
IsStudent
</th>
<th>
Actions
</th>
</tr>
#if (Model.Count() == 0)
{
<tr>
<td colspan=7>
There are currently no trespassers in the trespass database.
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
#Html.DisplayFor(modelItem => item.School)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsStudent)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.PersonId }) |
#Html.ActionLink("Details", "Details", new { id = item.PersonId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.PersonId })
</td>
</tr>
}
}
</table>
</div>
</div>
And the partial view:
#model IEnumerable<TrespassTracker.Models.PersonViewModel>
<table>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Gender
</th>
<th>
Date of Birth
</th>
<th>
Is a Student?
</th>
<th>
Actions
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsStudent)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
From my research I found the usual suspect to be the missing link to the jquery script in the partial, but I had that. I checked the network tab on my wed dev tools and found it is being called. What else could the problem be?

the script won't cause any problem and the only thing I see wrong here is the table. you are trying yo fill the table with other table which returns a table, use a div instead to update the ajax form (search result):
<div id="indexSearchResults">
<table>
..........
</table>
</div>

Try this
<div class="page">
<div class="middle-col-comment-mod">
<h2>Search Existing Trespassers</h2>
<div id="search">
#using (Ajax.BeginForm("_SearchResult", "Search", null, new AjaxOptions { HttpMethod = "Post", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "indexSearchResults" }))
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
<input type="submit" name="submit" class="skbutton" value="Search" />
</div>
}
</div>
#if (Model.Count() == 0)
{
<label>There are currently no trespassers in the trespass database. </label>
}
else
{
foreach (var item in Model)
{
#Html.Partial("__SearchResult",item)
}
</div>
</div>

How 'bout to use jQuery do reload your result content, instead Post from your form? You can named some div with an ID and uses it as reference do jQuery.load() (considering you're using that ViewModel you passed into Index action):
1.View
#model YourModel
<!-- ... -->
<div id="search">
#using (Ajax.BeginForm("MainPostAction", "ControllerName", FormMethod.Post, new { id = "yourFormID" })
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBoxFor(model => model.FirstName)
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBoxFor(model => model.LastName, new { style = "margin-right: 15px;" })
<input type="button" name="submit" id="searchButton" class="skbutton" value="Search" />
</div>
<div id="results"></div>
}
</div>
Javascript:
$(document).ready(function() {
$('#searchButton').click(function(event) {
$('#results').load('#Url.Action('_SearchResult', 'Search')', $('#yourFormID').serialize());
});
}
Your action remains the same.
How 'bout it?

Related

Display Required Error message IEnumerable Model

On the same view I am returning a list. Also, I have [HttpPost] to create new entry.
When the model is not valid, The ValidationSummary shows that expenseName is Required.
I would like to show Model required error Messages near each field in my View. asp-Validation-for was working when I didn't have IEnumerable model. What I have to do so I can see the validation error messages using IEnumerable model? (etc. for expenseName)
Model
[Key]
public int expenseId { get; set; }
[Column(TypeName = "nvarchar(50)")]
[Required(ErrorMessage = "The field 'Expense Name' is required")]
public string expenseName { get; set;}
public double price { get; set; }
public bool isStandard { get; set; }
public DateTime? date { get; set; }
View
#model IEnumerable<ExpenseTracker.Models.Expenses>
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#{
ViewData["Title"] = "Index";
}
<form method="post" enctype="multipart/form-data" asp-controller="Expenses" asp-action="Index">
<div>
<label for="files" class="lbl-select-file">Select Expense File</label>
<input id="files" name="postedFiles" class="btn-uploader" type="file">
</div>
<label class="expense-name-lbl" for="expenseName">Expense Name</label>
<input type="text" name="expenseName" class="expense-name-input" id="expenseName" />
**<span asp-validation-for=" " class="text-danger"></span>**
<div class="form-group form-check">
<label class="form-check-label checkbox-isStandard-form">
<input class="form-check-input" type="checkbox" name="chkeco" title="Check this if the bill is monthly/yearly" /> Is Standard?
</label>
</div>
<input type="submit" class="btn btn-success btnColor-expenses" value="Upload" />
<label id="fileName"></label>
<span class="uploaded-file">#Html.Raw(ViewBag.Message)</span>
</form>
<table class="table table-text">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.expenseName)
</th>
<th>
#Html.DisplayNameFor(model => model.price)
</th>
<th>
#Html.DisplayNameFor(model => model.isStandard)
</th>
<th>
#Html.DisplayNameFor(model => model.date)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.expenseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
<input type="checkbox" class="checkbox-isStandard" checked="#item.isStandard" />
</td>
<td>
#if (item.date.HasValue)
{
DateTime? datetimeToDate = #item.date;
string FormattedDate = datetimeToDate.Value.ToString("dd-MM-yyyy");
<label>#FormattedDate</label>
}
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.expenseId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.expenseId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.expenseId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
[PreventDuplicateRequest]
public async Task<IActionResult> Index(IFormCollection formCollection, string expenseName,
List<IFormFile> postedFiles, [Bind("expenseName,price,isStandard,date")] Expenses expenses)
{
if (ModelState.IsValid)
{
......
return View(await _context.Expenses.ToListAsync());
}
else
{
return View(await _context.Expenses.ToListAsync());
}
You can create a ViewModel which contains a List<Expenses>(you wanna display in the view) and a Expenses(you wanna upload to the controller).
ViewModel
public class ExpensesViewModel
{
//Pass the value to this parameter in the get method to display on the page
public List<Expenses> ListModel { get; set; }
public Expenses model { get; set; }
}
Then change your view code like:
#model ExpensesViewModel
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#{
ViewData["Title"] = "Index";
}
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Show">
<div>
<label for="files" class="lbl-select-file">Select Expense File</label>
<input id="files" name="postedFiles" class="btn-uploader" type="file">
</div>
<div class="form-group">
<label class="expense-name-lbl" for="expenseName">Expense Name</label>
<input type="text" \ class="expense-name-input" asp-for=#Model.model.expenseName />
<span asp-validation-for="#Model.model.expenseName" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label checkbox-isStandard-form">
<input class="form-check-input" type="checkbox" name="chkeco" title="Check this if the bill is monthly/yearly" /> Is Standard?
</label>
</div>
<input type="submit" class="btn btn-success btnColor-expenses" value="Upload" />
<label id="fileName"></label>
<span class="uploaded-file">#Html.Raw(ViewBag.Message)</span>
</form>
<table class="table table-text">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.model.expenseName)
</th>
<th>
#Html.DisplayNameFor(model => model.model.price)
</th>
<th>
#Html.DisplayNameFor(model => model.model.isStandard)
</th>
<th>
#Html.DisplayNameFor(model => model.model.date)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.ListModel)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.expenseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
<input type="checkbox" class="checkbox-isStandard" checked="#item.isStandard" />
</td>
<td>
#if (item.date.HasValue)
{
DateTime? datetimeToDate = #item.date;
string FormattedDate = datetimeToDate.Value.ToString("dd-MM-yyyy");
<label>#FormattedDate</label>
}
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.expenseId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.expenseId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.expenseId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Finally, You can validate your expenseName property.
You can try to add this validation js.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>

.NET MVC Ajax.ActionLink not returning partial view

I have been researching and trying multiple failed attempts FOR DAYS to get my partial view to display within my main view using Ajax.actionlink. When using the developer tools and viewing the Network tab, I do see the request. When clicking on Preview, I can see the correct data within the partial view. No jQuery errors.
View
#model IEnumerable<NS.Models.FeeAuth>
#using (Html.BeginForm())
{
<p>
<span class="glyphicon glyphicon-search"></span> Find by Last Name: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}
<div class="table-responsive">
<table class="table table-condensed" style="border-collapse:collapse;">
<tr>
<th>
#Html.LabelFor(m => m.First().ID)
</th>
<th>
#Html.ActionLink("Request ID", "ApprovalIndex", new { sortOrder = ViewBag.RequestIDSortParam })
</th>
<th>
#Html.Label("emplid", "Student Emplid")
</th>
</tr>
#{int i = 0;}
#foreach (var item in Model)
{
<tr data-toggle="collapse" data-parent="#collapse1_#i" data-target="#collapse1_#i" class="accordion-toggle">
<td>
#Ajax.ActionLink(Html.Encode(item.ID),
"SelectedSTRMS",
"FeeAuth",
new { id = item.ID, requestId = item.requestID },
new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "SelectedSTRMList" + i,
InsertionMode = InsertionMode.Replace
})
</td>
<td>
#Html.DisplayFor(modelItem => item.requestID)
</td>
<td>
#Html.DisplayFor(modelItem => item.emplid)
</td>
</tr>
<tr>
<td colspan="6" class="hiddenRow">
<div class="accordion-body collapse" id="collapse1_#i">
<div id="SelectedSTRMList_#i">
</div>
</div>
</td>
</tr>
i++;
}
</table>
</div>
Partial View
<table>
<tr>
<td>
<ul>
#foreach (var s in (List<string>)ViewBag.SemesterInfo)
{
<li style="padding-bottom:20px;">#s</li>
}
</ul>
</td>
</tr>
</table>
Jquery in _Layout.cshtml
<script src="~/Scripts/jquery-2.1.3.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-migrate-1.2.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
Controller
[HttpGet]
public PartialViewResult SelectedSTRMS(int id, int requestId)
{
FeeAuthWithCommentsViewModel feeauth = new FeeAuthWithCommentsViewModel();
feeauth.FeeAuth = db.FeeAuths.Find(id);
int feeauthID = id;
List<string> GetSTRM = new List<string>();
GetSTRM = db.vw_GetSTRMs.Where(v => v.FeeAuthID == feeauthID).Select(v => v.DESCR).ToList();
if (GetSTRM.Count > 0)
{
ViewBag.SemesterInfo = GetSTRM.ToList();
}
else
{
ViewBag.SemesterInfo = new List<string> { "No STRM Selected" };
}
return PartialView("_SelectedSTRMS");
}
Your update target is:
UpdateTargetId = "SelectedSTRMList" + i,
But your div id is:
<div id="SelectedSTRMList_#i">
In other words, you're either missing an _ in the update target string or you need to remove the _ in your div id.

create and index views combined in 1 view

I want to be able to add players and upon addition in the same I want to display them in a table similar to what page Index view offers. so what I did is combine the index and create views in 1 page.
but when debugging I'm have a resource cannot be found error.
can some one please correct where I'm going wrong
Index View:
#model IEnumerable<sportsMania.player>
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>category</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.Label("Player Name")
<div class="col-md-10">
#Html.Editor("Player Name")
</div>
</div>
<div class="form-group">
#Html.Label("Team")
<div class="col-md-10">
#Html.DropDownList("team", ViewBag.team as SelectList)
</div>
</div>
<div class="form-group">
#Html.Label("Position")
<div class="col-md-10">
#Html.Editor("position")
</div>
</div>
<div class="form-group">
#Html.Label("Email")
<div class="col-md-10">
#Html.Editor("email")
</div>
</div>
<div class="form-group">
#Html.Label("Type")
<div class="col-md-10">
#Html.Editor("type")
</div>
</div>
<div class="form-group">
#Html.Label("Height")
<div class="col-md-10">
#Html.Editor("height")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.playerName)
</th>
<th>
#Html.DisplayNameFor(model => model.team)
</th>
<th>
#Html.DisplayNameFor(model => model.position)
</th>
<th>
#Html.DisplayNameFor(model => model.email)
</th>
<th>
#Html.DisplayNameFor(model => model.type)
</th>
<th>
#Html.DisplayNameFor(model => model.height)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.playerName)
</td>
<td>
#Html.DisplayFor(modelItem => item.team)
</td>
<td>
#Html.DisplayFor(modelItem => item.position)
</td>
<td>
#Html.DisplayFor(modelItem => item.email)
</td>
<td>
#Html.DisplayFor(modelItem => item.type)
</td>
<td>
#Html.DisplayFor(modelItem => item.height)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
playerController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace sportsMania.Controllers
{
public class playerController : Controller
{
sportsEntities db = new sportsEntities();
[HttpPost]
public ActionResult Index()
{
var data = from p in db.Teams
select p.teamName;
SelectList list = new SelectList(data);
ViewBag.team = list;
return View(db.players.ToList());
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(player player)
{
if (ModelState.IsValid)
{
player newRecord = new player();
newRecord.playerName = Request.Form["Player Name"];
newRecord.position = Request.Form["position"];
newRecord.type =Request.Form[ "type"];
newRecord.team =Request.Form[ "team"];
newRecord.email = Request.Form["email"];
newRecord.height = Request.Form["height"];
db.players.Add(player);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(player);
}
}
}
why I am doing this? because I don't want every time the user have to add a Player he should be redirected to the create view, I want when user finishes adding players he will hit a button "done adding" and will be redirected home.

How to pass search criteria to controller using MVC AJAX PagedList

I'm creating Advanced Search using MVC. What I mean by Advanced Search is user can do combination search, for example, user can search by category = 'Child' and name contains 'A' or age <= 10. then the result is displayed using MVC PagedList.
I followed UnobtrusiveAjax tutorial based on example from PagedList source. I defined 2 files, Index.cshtml for View and _List.cshtml for PartialView. Index contains search criteria and a button to add more clause.
and _List contains table for displaying the result using AJAX
The problem is after I filtered by code for example contains 'A' and click search then navigate to page 2 the filter value is missing and it will display code which not contains 'A'. How to solve this problem?
ViewModel:
public class WorkflowStateListViewModel
{
public IEnumerable<string> FilterField { get; set; }
public IEnumerable<string> FilterOperator { get; set; }
public IEnumerable<string> FilterString { get; set; }
public IEnumerable<string> FilterLogical { get; set; }
public PagedList<WorkflowStateListDetailViewModel> WorkflowStateListDetailVM { get; set; }
public int? Page { get; set; }
}
Controller:
public ActionResult Filter(WorkflowStateListViewModel workflowStateListVM, int? page)
{
var workflowStatesQuery = from ws in db.WorkflowStates
where ws.RowStatus == true
select ws;
if (workflowStateListVM.FilterField != null)
{
for (int i = 0; i < workflowStateListVM.FilterField.Count(); i++)
{
workflowStatesQuery = DoFilter(workflowStatesQuery, workflowStateListVM.FilterField.ElementAt(i), workflowStateListVM.FilterOperator.ElementAt(i), workflowStateListVM.FilterString.ElementAt(i));
}
}
workflowStatesQuery = workflowStatesQuery.OrderBy(ws => ws.Code);
var workflowStateListDetailVM = from ws in workflowStatesQuery
select new WorkflowStateListDetailViewModel()
{
WorkflowStateID = ws.WorkflowStateID,
Code = ws.Code,
Name = ws.Name,
Level = ws.Level,
PIC = ws.PIC
};
int pageNumber = (page ?? 1);
return PartialView("_List", workflowStateListDetailVM.ToPagedList(pageNumber, 5));
}
Index.cshtml
#model ViewModels.WorkflowStateListViewModel
#using (Ajax.BeginForm("Filter", "WorkflowState",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
UpdateTargetId = "workflowStateList"
},
new { #class = "form-inline" }))
{
<div id="clauses">
</div>
<p>
<div class="form-group">
#Html.DropDownList("FilterField", new SelectList(Model.FilterField), new { #class = "form-control" })
</div>
<div class="form-group">
#Html.DropDownList("FilterOperator", new SelectList(Model.FilterOperator), new { #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.FilterString, new { #class = "form-control" })
</div>
<input type="submit" value="Search" class="btn btn-default" />
</p>
<p>
<div class="form-group">
<span class="glyphicon glyphicon-plus-sign"></span> Add new clause
</div>
</p>
<div id="workflowStateList">
#{ Html.RenderPartial("_List", Model); }
</div>
}
_List.cshtml
#model JOeBilling.ViewModels.WorkflowStateListViewModel
#using PagedList.Mvc;
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<tr>
<th></th>
<th>
Code
</th>
<th>
Name
</th>
<th>
Level
</th>
<th>
PIC
</th>
</tr>
#foreach (var item in Model.WorkflowStateListDetailVM)
{
<tr>
<td>
<span class="glyphicon glyphicon-pencil"></span>
<span class="glyphicon glyphicon-eye-open"></span>
<span class="glyphicon glyphicon-remove"></span>
</td>
<td>
#Html.DisplayFor(modelItem => item.Code)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Level)
</td>
<td>
#Html.DisplayFor(modelItem => item.PIC)
</td>
</tr>
}
</table>
</div>
<br />
Page #(Model.WorkflowStateListDetailVM.PageCount < Model.WorkflowStateListDetailVM.PageNumber ? 0 : Model.WorkflowStateListDetailVM.PageNumber) of #Model.WorkflowStateListDetailVM.PageCount
#Html.PagedListPager(Model.WorkflowStateListDetailVM,
page => Url.Action("Filter", new { page }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "workflowStateList" }))
UPDATE
UPDATE 2
UPDATE 3 Response tab
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<tr>
<th></th>
<th>
Code
</th>
<th>
Name
</th>
<th>
Level
</th>
<th>
PIC
</th>
<th>
Created By
</th>
<th>
Created Date
</th>
<th>
Modified By
</th>
<th>
Modified Date
</th>
</tr>
<tr>
<td>
<span class="glyphicon glyphicon-pencil"></span>
<span class="glyphicon glyphicon-eye-open"></span>
<span class="glyphicon glyphicon-remove"></span>
</td>
<td>
A06
</td>
<td>
Preparing Task Code
</td>
<td>
6
</td>
<td>
</td>
<td>
JKTWLA
</td>
<td>
28/04/2014 4:24:52 PM
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<span class="glyphicon glyphicon-pencil"></span>
<span class="glyphicon glyphicon-eye-open"></span>
<span class="glyphicon glyphicon-remove"></span>
</td>
<td>
A07
</td>
<td>
Closed
</td>
<td>
7
</td>
<td>
</td>
<td>
JKTWLA
</td>
<td>
28/04/2014 4:25:06 PM
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<span class="glyphicon glyphicon-pencil"></span>
<span class="glyphicon glyphicon-eye-open"></span>
<span class="glyphicon glyphicon-remove"></span>
</td>
<td>
C01
</td>
<td>
New Invoice
</td>
<td>
1
</td>
<td>
</td>
<td>
JKTWLA
</td>
<td>
13/06/2014 10:49:00 AM
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</div>
<br />
Page 2 of 2
<div class="pagination-container"><ul class="pagination"><li class="PagedList-skipToPrevious"><a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#workflowStateList" href="/WorkflowState/Filter?page=1" rel="prev">«</a></li><li><a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#workflowStateList" href="/WorkflowState/Filter?page=1">1</a></li><li class="active"><a>2</a></li></ul></div>

Post multiple data from an loaded form ajax mvc 4

I have a form like this
<table>
<thead>
<tr>
<th>Tên học sinh </th>
<th>Giáo lý viên </th>
<th>Năm Học</th>
<th>Điểm TB Học Kỳ 1 </th>
<th>Điểm TB Học Kỳ 2 </th>
<th>Điểm Tổng Kết Năm Học </th>
<th>Lớp </th>
</tr>
</thead>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset class="form-horizontal">
<tbody id="addDetails">
<tr>
<td>
#Html.DropDownList("HocSinhId", String.Empty)
#Html.ValidationMessageFor(model => model.HocSinhId, null, new { #class = "help-inline" })
</td>
<td>
#Html.DropDownList("GiaoLyVienId", String.Empty)
#Html.ValidationMessageFor(model => model.GiaoLyVienId, null, new { #class = "help-inline" })
</td>
<td>
#Html.TextBoxFor(model => model.NamHoc)
#Html.ValidationMessageFor(model => model.NamHoc, null, new { #class = "help-inline" })
</td>
<td>
#Html.EditorFor(model => model.DiemTBHK1)
#Html.ValidationMessageFor(model => model.DiemTBHK1, null, new { #class = "help-inline" })
</td>
<td>
#Html.EditorFor(model => model.DiemTBHK2)
#Html.ValidationMessageFor(model => model.DiemTBHK2, null, new { #class = "help-inline" })
</td>
<td>
#Html.EditorFor(model => model.DiemTongKetNamHoc)
#Html.ValidationMessageFor(model => model.DiemTongKetNamHoc, null, new { #class = "help-inline" })
</td>
<td>
#Html.DropDownList("LopId", String.Empty)
#Html.ValidationMessageFor(model => model.LopId, null, new { #class = "help-inline" })
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
#Ajax.ActionLink("Add", "AddDetails", new AjaxOptions
{
HttpMethod = "GET",
OnSuccess = "successCall",
#*UpdateTargetId = "addDetails",
InsertionMode = InsertionMode.InsertAfter,*#
})
</td>
</tr>
<tr>
<td colspan="6">
#* *#
<input type="submit" value="Lưu thông tin" class="button" />
</td>
</tr>
</tfoot>
</fieldset>
}
</table>
After click Ajax link "Add" it will insert new row to input new data.
Image: http://i808.photobucket.com/albums/zz1/nquangkhaiDST/Postmultipledata_zps5364f0a0.png
The Question is: When I submit to server, it just post the first data, not the data after i click "Add". How i can get all the data even field from ajax to post back to server.
Anyone know how to post all the data even the data of ajax. Thanks a lots
Assuming you'll be adding that same type of object when you click Add, what you need to do is accept an array of your model object in your Post controller parameter.
[HttpPost]
public ActionResult(MyObject[] objects)
{
// do something
}
did you check your html on client side.... while submitting from client side you have to make sure that that the controls added on the page must have naming convention like
<input type="text" value="" name="IncomeDetails[0].IncomeCode" id="IncomeDetails_0__IncomeCode" class="incomeCode valid" disabled="disabled">
on the first row and
<input type="text" disabled="disabled" class="incomeCode valid" id="IncomeDetails_1__IncomeCode" name="IncomeDetails[1].IncomeCode" value="">
on the second row then only while submitting you can get full list of objects.

Resources