why the ajax request sent as non-ajax? - asp.net-mvc-4

i have the following index view
#model VirtualCampus2.Models.EmployeeViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#using(Ajax.BeginForm("GetEmployee", "Employee",
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
OnSuccess = "updateDivList",
UpdateTargetId = "divList" }))
{
#Html.DropDownListFor(m=>m.id, Model.DDLCollecton)
<input type="text" name="SearchString" />
<input type="submit" value="search" />
}
<div id="divList">
#Html.Partial("_EmployeeList", Model.Employees);
</div>
<script type="text/javascript">
function updateDivList() {
$('#divList').html();
}
</script>
its controller :
public class EmployeeController : Controller
{
//
// GET: /Employee/
testdbEntities db = new testdbEntities();
public ActionResult Index()
{
List<SelectListItem> ddlColl = new List<SelectListItem>
{
new SelectListItem{ Text="By Emp No", Value="1", Selected=true},
new SelectListItem{ Text="By Name", Value="2"}
};
var employees = db.Employees.Select(e => new EmployeeModel
{
EmpID=e.EmpId,
FirstName=e.FirstName,
LastName=e.LastName,
DeptId=e.DepartmentId,
DepartmentName=e.Department.Name
});
EmployeeViewModel evm = new EmployeeViewModel { DDLCollecton = ddlColl, Employees = employees };
return View(evm);
}
public ActionResult GetEmployee(string id, string SearchString)
{
IEnumerable<EmployeeModel> results=null;
if (id == "1")
{
var searchID = ( SearchString == "" ) ? 0 : int.Parse(SearchString);
results = db.Employees.Where( e => ( SearchString == "" || e.EmpId == searchID ) )
.Select(e => new EmployeeModel
{
EmpID = e.EmpId,
FirstName = e.FirstName,
LastName = e.LastName,
DeptId = e.DepartmentId,
DepartmentName = e.Department.Name
}).ToList();
}
else
{
}
return PartialView("_EmployeeList", results);
}
when i request the ajax it sends request as non-ajax call but gets the data as a regular http request, as shown on this video
why it happens and how do i fix this?

Related

Use and ArrayList to display data from an MVC Controller to a Razor Page

I'm pretty new to working with Array Lists and would like to learn how to display data from the Controller that has an Array in the method to the MVC Razor Page. I'm creating a login that works just fine, but would like to display captured data from Active Directory to the UserLoginData.CSHTML page. I read that the best way is through the model. Any help would be greatly appreciated! (I just want the ArrayList in a table on the Razor data Page.)
Controller:
enter code here
public ActionResult UserLoginData(string username, string LblUserName, string
UserName, ArrayList AuthorizationGroups)
{
UserLoginModel model = new UserLoginModel();
UserName = username;
ViewBag.UserName = UserName;
model.UserName = UserName;
model.LblUserName = model.UserName;
model.AuthorizationGroups = AuthorizationGroups;
foreach (var item in AuthorizationGroups)
{
// Console.WriteLine(item);
model.item = item;
}
return View(model);
}
Model (Properties):
//Labels for UserLoginData:
public string LblUserName { get; set; }
public string LblTitle { get; set; }
public string LblPlantLocation { get; set; }
public string LblUserLoggedInTimeStamp { get; set; }
public string LblUserLoggedOutTimeStamp { get; set; }
public string LblDisplayName { get; set; }
public string LblEmail { get; set; }
//For the ArrayList of MemberGroups.
public ArrayList AuthorizationGroups { get; set; }
public ArrayList YardDogUserGroupMembers { get; set; }
public ArrayList MemberOfUserGroups { get; set; }
public ArrayList YardDogAdminGroupMembers { get; set; }
public object item { get; set; }
Razor CSHTML:
enter code here
#model PW_Login.Models.UserLoginModel
#{
Layout = null;
/*
WebGrid webGrid = new WebGrid(source: Model, canPage: true, canSort: true,
sortDirectionFieldName: "PlantLocation", rowsPerPage: 50);
webGrid.Pager(WebGridPagerModes.All);
*/
}
<!DOCTYPE html>
<html>
<head>
<link href="~/Content/UserLogin.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
#using (Html.BeginForm("UserLoginData", "LoginController", FormMethod.Post, new { id =
"LoginDataForm", Class = "LoginDataForm" }))
{
//Html.ListBoxFor(model=>model.AuthorizationGroups, Model.AuthorizationGroups)
// string UserName = Session["UserName"].ToString();
<label></label>
//Html.LabelFor(model => model.UserName, #Model.UserName)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.UserName)
</th>
<th>
#Html.DisplayNameFor(model => model.UserPlantLocation)
</th>
</tr>
<tr>
<td>
<!--- Html.DisplayFor(modelItem => item.AuthorizationGroups) -->
#foreach ( var item in Model.AuthorizationGroups)
{
#Html.DisplayNameFor(Modelitem=>item)
}
</td>
</tr>
</table>
}
</body>
</html>
Method that gets the info from AD in the Controller:
private void ShowUserInformation(SearchResult rs, string UserName)
{
UserLoginModel model = new UserLoginModel();
Cursor.Current = Cursors.Default;
model.UserName = UserName;
Session["UserName"] = UserName;
Session["LblUserName"] = UserName;
DateTime now = DateTime.Now;
string UserLoggedInTimeStamp = now.ToString();
model.LblUserLoggedInTimeStamp = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
//Push the UserName into the Label via the model.
if (rs.GetDirectoryEntry().Properties["samaccountname"].Value != null)
model.LblUserName = "Username : " +
rs.GetDirectoryEntry().Properties["samaccountname"].Value.ToString();
if (rs.GetDirectoryEntry().Properties["title"].Value != null)
model.LblTitle = "Title : " +
rs.GetDirectoryEntry().Properties["title"].Value.ToString();
//description returns null... need to find out active directory folder/subfolder.
if (rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value != null)
//PhysicalDeliveryOfficeName returns 110.
model.LblPlantLocation = "PlantLocation : " +
rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString();
if (rs.GetDirectoryEntry().Properties["member"].Value != null)
model.LblMemberGroup = "Member : " +
rs.GetDirectoryEntry().Properties["member"].Value.ToString();
//DisplayName or DistinguishedName is what I do believe is in the security group
"YardDogUser" or "YardDogAdmin".
if (rs.GetDirectoryEntry().Properties["distinguishedName"].Value != null)
model.LblDistinguishedName = "distinguishedName : " +
rs.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString();
//NULL...
if (rs.GetDirectoryEntry().Properties["YardDogAdmin"].Value != null)
model.LblYardDogAdmin = "YardDogAdmin : " +
rs.GetDirectoryEntry().Properties["YardDogAdmin"].Value.ToString();
if (rs.GetDirectoryEntry().Properties["displayname"].Value != null)
model.LblDisplayName = "Display Name : " +
rs.GetDirectoryEntry().Properties["displayname"].Value.ToString();
if (rs.GetDirectoryEntry().Properties["email"].Value != null)
model.lblEmail = "Email Address : " +
rs.GetDirectoryEntry().Properties["email"].Value.ToString();
/*
//Member Of Office 365 Groups. Use if needed!
///ArrayList MemberOfGroups = new ArrayList();
var MemberOfGroups = new ArrayList(); //perfered way of writing.
string Ret1 = string.Empty;
foreach (object memberOf in rs.GetDirectoryEntry().Properties["memberOf"])
{
MemberOfGroups.Add(Ret1 += " Member Of : " + memberOf.ToString() + "\n");
}
*/
//Get Security Groups that User belongs to. Note: Doesn't show other groups (won't
show YardDogAdmin).
ArrayList SecurityGroups = new ArrayList();
foreach (IdentityReference group in
System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
{
SecurityGroups.Add(group.Translate(typeof(NTAccount)).ToString());
}
//model doesn't show the correct datetime on these.
model.LblUserLoggedInTimeStamp = model.UserLoggedInTimeStamp.ToString();
model.LblUserLoggedOutTimeStamp = model.UserLoggedOutTimeStamp.ToString();
/******************************************************************************/
//Search to see if this group exists that starts with "YardDog".
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
ArrayList FoundYardDogAdmin = new ArrayList();
ArrayList SecurityGroupsFound = new ArrayList();
// define a "query-by-example" principal - here, we search for a GroupPrincipal
// and with the name like some pattern
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
qbeGroup.Name = "YardDog*"; //Find all the User Groups for this User that is
logging in.
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
string Ret4 = string.Empty;
// find all matches
foreach (var found in srch.FindAll())
{
FoundYardDogAdmin.Add(Ret4 += " GroupFound : " + found.ToString() + "\n");
SecurityGroupsFound.Add(Ret4 += " GroupFound : " + qbeGroup.ToString() +
"\n");
}
//Count where the User's Display Name exists is needed next. We could do this here
or when we get all the Groups.
}
//Search for all User's of YardDogAdmin Group and list them in the ArrayList.
/*
using PrincipalContext ctxDomain = new PrincipalContext(ContextType.Domain);
{
// get the group you're interested in
GroupPrincipal GroupMembers = GroupPrincipal.FindByIdentity("YardDogAdmin");
ArrayList GroupMembersArray = new ArrayList();
// iterate over its members
foreach (Principal principal in GroupMembers.Members)
{
GroupMembersArray.Add(principal);
}
}
*/
/* Below works, finds all in YardDogAdmin's, YardDogUser's (Finds security groups by
string search). Use if needed.*/
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
//Groups to validate against for current User.
var GroupYardDogAdminPrincipalName = "YardDogAdmin";
var GroupYardDogUserPrincipalName = "YardDogUser";
//Find the current User's Groups.
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, UserName);
//Find all User's within these Groups.
GroupPrincipal YardDogAdminMembers = GroupPrincipal.FindByIdentity(ctx,
GroupYardDogAdminPrincipalName);
GroupPrincipal YardDogUserMembers = GroupPrincipal.FindByIdentity(ctx,
GroupYardDogUserPrincipalName);
//UserGroups that the User logged in belongs to.
if (user != null)
{
var MemberOfUserGroups = new ArrayList();
model.MemberOfUserGroups = MemberOfUserGroups;
var groups = user.GetAuthorizationGroups();
foreach (GroupPrincipal group in groups)
{
MemberOfUserGroups.Add(group);
}
if (MemberOfUserGroups.Contains("YardDogAdmin"))
{
//Pass to the model YardDogAdmin exists for this user (AdminFlag translates to
LocationData table).
model.LblYardDogAdmin = "Y";
model.AdminFlag = "Y";
}
else
{
model.LblYardDogAdmin = "N";
model.AdminFlag = "N";
}
//Get the Members of YardDogAdmin and their warehouse locations.
if (YardDogAdminMembers != null)
{
var YardDogAdminGroupMembers = new ArrayList();
model.YardDogAdminGroupMembers = YardDogAdminGroupMembers;
foreach (Principal principal in YardDogAdminMembers.Members)
{
rs = SearchUserByDisplayName(principal.DisplayName.ToString());
YardDogAdminGroupMembers.Add(principal.DisplayName + " " +
rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString() + "
YardDogAdmin");
}
}
//Get the Members of YardDogUser and their location.
if (YardDogUserMembers != null)
{
var YardDogUserGroupMembers = new ArrayList();
model.YardDogUserGroupMembers = YardDogUserGroupMembers;
foreach (Principal principal in YardDogUserMembers.Members)
{
rs = SearchUserByDisplayName(principal.DisplayName.ToString());
YardDogUserGroupMembers.Add(principal.DisplayName + " " +
rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString() + "
YardDogUser");
}
}
}
}
Just create TempData[] in the controller from one controller action result to another and then into the model also. After that you can access the TempData and keep it as needed for that session. Then on the Login Data Page, loop through the objects from the TempData or model properties to display in labels.
enter code here
#model PW_Login.Models.UserLoginModel
#{
Layout = null;
string UserName = TempData["UserName"].ToString();
string PlantLocation = TempData["UserPlantLocation"].ToString();
string UserLoggedInTimeStamp =
TempData["UserLoggedInTimeStamp"].ToString();
//Get the TempData Sessions and write them out.
var SecurityGroups = TempData["SecurityGroups"];
var MemberOfUserGroups = TempData["MemberOfUserGroups"];
var YardDogAdminGroupMembers = TempData["YardDogAdminGroupMembers"];
var YardDogUserGroupMembers = TempData["YardDogUserGroupMembers"];
TempData.Keep(UserLoggedInTimeStamp.ToString());
TempData.Keep(SecurityGroups.ToString());
TempData.Keep(MemberOfUserGroups.ToString());
TempData.Keep(YardDogAdminGroupMembers.ToString());
TempData.Keep(YardDogUserGroupMembers.ToString());
// PW_Login.Models.UserLoginModel LoginModel;
// LoginModel.SecurityGroups = SecurityGroups;
}
<!DOCTYPE html>
<html>
<head>
<link href="~/Content/UserLogin.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<asp:Panel runat="server" ID="Panel2" HorizontalAlign="Center">
<img id="PM_Logo" src="~/images/PremiumWatersLogo.PNG" />
</asp:Panel>
<h2>User Login Groups</h2><br /><br />
<div id="time"></div>
<SCRIPT LANGUAGE="Javascript">
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" +
s; //Get the time.
document.getElementById('time').innerHTML = "Date: " + today;
//Get the Date.
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
</SCRIPT>
#using (Html.BeginForm("UserLoginData", "LoginController", FormMethod.Post,
new { id = "LoginDataForm", Class = "LoginDataForm" }))
{
<dv id="FlexLoginDataTables" class="FlexLoginDataTables">
<table id="LoginDataTable" class="LoginDataTable">
<tr>
<th>
#Html.LabelForModel(UserName, "User Name: ")
</th>
</tr>
<tr>
<td>
#foreach (var group in #Model.SecurityGroups)
{
<label id="LoginDataLabel"
class="LoginDataLabel">#group.ToString()</label><br />
}
</td>
</tr>
</table>
<table id="LoginDataTable" class="LoginDataTable">
<tr>
<th>
#Html.LabelFor(m => m.YardDogAdminGroupMembers)
</th>
</tr>
<tr>
<td>
#foreach (var group in #Model.YardDogAdminGroupMembers)
{
<label id="LoginDataLabel"
class="LoginDataLabel">#group.ToString()</label><br />
}
</td>
</tr>
</table>
<table id="LoginDataTable" class="LoginDataTable">
<tr>
<th>
#Html.LabelFor(m => m.YardDogUserGroupMembers)
</th>
</tr>
<tr>
<td>
#foreach (var group in #Model.YardDogUserGroupMembers)
{
<label id="LoginDataLabel"
class="LoginDataLabel">#group.ToString()</label><br />
}
</td>
</tr>
</table>
</dv>
<table>
<tr>
<th>
#Html.LabelFor(model => model.UserLoggedInTimeStamp,
#Model.UserLoggedInTimeStamp)
</th>
<td>
#Html.Label(#Model.UserLoggedInTimeStamp.ToString())
</td>
</tr>
</table>
<table id="LoginDataTable" class="LoginDataTable">
<tr>
<th>
</th>
<td>
</td>
</tr>
</table>
}
</body>
</html>

how to pass posted file using ajax beginform in mvc?

I have following in my partial view.
#using (Ajax.BeginForm("xyz", "xyz", new AjaxOptions { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
<input type="file" name="FileName" id="FileName" style="width:240px" />
<input type="submit" value="Upload" onclick="submit()" />
}
in my controller following is method.
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult xyz(HttpPostedFileBase FileName)
{
var httpPostedFileBase = Request.Files["FileName"];
if (httpPostedFileBase != null && httpPostedFileBase.ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(httpPostedFileBase.FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/SavedFiles"), extension);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
httpPostedFileBase.SaveAs(path1);
}
ViewData["Status"] = "Success";
return Json("test", JsonRequestBehavior.AllowGet);
}
From the above i should get the file on my controller that is posted but it does not give me file instead gives null on controller action.
Please suggest.

How can I return a model with an ActionLink?

I'm trying to get a model in a view and pass it to another controller but the model is null when passed to the other controller.
Controller - Here I send the model to render in my view:
[HttpPost]
public PartialViewResult Index(ReportesTabularesViewModel ModeloInput)
{
GetDatosTabularReportInput input = new GetDatosTabularReportInput { IdSensor = ModeloInput.sensor, FechaInicio = ModeloInput.FechaInicio, FechaFinal = ModeloInput.FechaFinal };
ReportesTabularesViewModel Modelo = new ReportesTabularesViewModel();
var Lista = new CaelusReporting.Datos.DatosApp().GetDatosTabularReport(input);
var s = Modelo.Sensores;
ViewBag.Sensores = s;
Modelo.Datos = Lista.GroupBy(x => x.Fecha).Select(y => new DatosViewModel
{
Fecha = y.Key,
EstacionSensorSensorNombre = y.First().EstacionSensorSensorNombre,
Datos = y
}
);
ViewBag.Modelo = ModeloInput;
return PartialView(Modelo);
}
View:
#model CaelusReporting.Web.Models.ViewModels.Datos.ReportesTabularesViewModel
#{
ViewData["temp"] = ViewBag.Modelo;
ViewBag.Title = Model.Datos.Select(y => y.EstacionSensorSensorNombre).FirstOrDefault();
List<CaelusReporting.Sensores.Dto.SensoresDto> sensores = ViewBag.Sensores;
}
<a class="menu-bar" data-toggle="collapse" href="#menu">
<span class="bars"></span>
</a>
<div class="collapse menu" id="menu">
<div class="list-inline">
#using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "Update", HttpMethod = "POST", InsertionMode = InsertionMode.Replace }))
{
<label>Sensor: </label>
<select data-placeholder="Escoja las estaciones" class="chosen-select-width" tabindex="8" name="sensor">
#foreach (var item in sensores.Where(x => x.estado == true))
{
<option value=#item.Id>#item.nombre</option>
}
</select>
<label>Fecha de Inicio: </label>
#Html.TextBoxFor(m => m.FechaInicio, null, new { type = "datetime-local", style = "max-width:235px; max-height:20px" })
<label>Fecha de Final: </label>
#Html.TextBoxFor(m => m.FechaFinal, null, new { type = "datetime-local", style = "max-width:235px; max-height:20px" })
<input id="Submit1" type="submit" value="Ver" />
}
Get Report in PDF
Get Report in XLS
Get Report in DOC
Get Report in CSV
</div>
</div>
Another controller - Here I try to import report that is in:
public ActionResult ExportReport(string DocType)
{
ReportesTabularesViewModel test = ViewData["temp"] as ReportesTabularesViewModel;
GetDatosTabularReportInput input = new GetDatosTabularReportInput { IdSensor = test.sensor, FechaInicio = test.FechaInicio, FechaFinal = test.FechaFinal };
var Lista = new CaelusReporting.Datos.DatosApp().GetDatosTabularReport(input);
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reportess"), "Reporte.rpt"));
rd.SetDataSource(Lista);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
switch (DocType)
{
case "PDF":
rd.Load(Path.Combine(Server.MapPath("~/Reportess"), "Reporte.rpt"));
try
{
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "ReportePDF.pdf");
}
catch (Exception ex)
{
throw;
}
case "DOC":
rd.Load(Path.Combine(Server.MapPath("~/Reportess"), "Reporte.rpt"));
try
{
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.WordForWindows);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/msword", "ReporteDOC.doc");
}
catch (Exception ex)
{
throw;
}
case "XLS":
rd.Load(Path.Combine(Server.MapPath("~/Reportess"), "Reporte.rpt"));
try
{
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.Excel);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/vnd.ms-excel", "ReporteDOC.xls");
}
catch (Exception ex)
{
throw;
}
case "CSV" :
rd.Load(Path.Combine(Server.MapPath("~/Reportess"), ""));
try
{
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.CharacterSeparatedValues);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "text/csv", "ReporteCSV.csv");
}
catch (Exception ex)
{
throw;
}
default:
return null;
}
}
You can not pass ViewData between requests (actions). You need to serialize data somehow, in querysting for example. You can use RouteValueDictionary to do this.
you need to create Model for action ActionResult ExportReport(string DocType) like this:
public class ExportReportModel
{
public string DocType {get; set;}
// all fields which you required from ReportesTabularesViewModel
}
then your action will looks like this ActionResult ExportReport(ExportReportModel model) and you can render such a links:
Get Report in PDF
you can also use anonymous objects, but in case when you have more than 3 parameters I will organize those in some kind of structure.

Partial View not refreshing?

My Controller method is
public ActionResult Index(string id = "All")
{
ViewBag.RefType = new SelectList(rep.getReferenceType());
List<Reference> reference = rep.getReference(id);
if (Request.IsAjaxRequest())
return PartialView("_ReferenceList", reference);
else
{
ViewBag.domain = "All";
return View(reference);
}
}
Second method calls the index
public ActionResult EditReference(Reference rf, int Dom)
{
Reference rf1 = null;
string dom = "";
if (ModelState.IsValid)
{
rf1 = rep.UpdateReference(rf);
if (Dom == 0)
{
dom = "All";
}
else
{
dom = rf1.Domain;
}
return RedirectToAction("Index", new { id =dom});
}
return View(rf1);
}
and my view is
#using (Ajax.BeginForm("EditReference", "Reference", new AjaxOptions { HttpMethod = "POST", OnSuccess = "closeDialog()", LoadingElementId = "divLoading" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
Html.RenderPartial("_Reference");
}
The problem is that the new edited data doesnt appear once the dialog is closed ...It displays the same old data...I tried another function
function closDlgAndRefresh{
$('.Dialog').dialog('close');
$('.ddlRndrPrtl').val($('.ddlRndrPrtl').val());
$('.ddlRndrPrtl').trigger('change');
}
and when I call this function onSuccess it does displays the data but the Index function is called twice which I don't wana do...Once when Index function is called from Edit function and 2nd when dropdown is triggered...
Got it fixed....
Forgot to add Updated TargetID in Ajax.BeginForm
#using (Ajax.BeginForm("EditReference", "Reference", new AjaxOptions { HttpMethod = "POST", LoadingElementId = "divLoading", InsertionMode = InsertionMode.Replace, UpdateTargetId = "DivTbl_Reference" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
Html.RenderPartial("_Reference");
}

Form post passes null model - .NET MVC 4

I am using this post as reference
I am trying to get the Model that I passed to the view to post back to the HttpPost method of the controller when the input is clicked. However, the model, which in this case is just List, is null when it posts back.
I have included my code for reference. This is just a project for testing random stuff out so I apologize for the crappy code.
I have the following View code: (showing the whole code for completness)
#{
ViewBag.Title = "Home Page";
}
#using TestApp.MyObjects
#model List<Contact>
#Ajax.ActionLink("Show About", "About", new { id = "1" }, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "contentDiv" })
#Ajax.ActionLink("Show Contact", "Contact", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "contentDiv" })
<div id="contentDiv"></div>
#using (Html.BeginForm())
{
<table>
#foreach (Contact c in Model)
{
<tr>
<td>
<button aboutnum0 = "#c.someValues[0]" aboutnum1 = "#c.someValues[1]" aboutnum2 = "#c.someValues[2]" class="nameButton">#c.name</button>
</td>
</tr>
}
</table>
<input value="#Model[0].name" />
<input value="#Model[0].name" />
<div id ="aboutContentDiv"></div>
<input type="submit" />
#ViewBag.myCoolValue
}
<script type="text/javascript">
$("button").click(function () {
$("#aboutContentDiv").empty();
$("#aboutContentDiv").append($("<div></div>").load("Home/About/" + $(this).attr("aboutnum0")));
$("#aboutContentDiv").append($("<div></div>").load("Home/About/" + $(this).attr("aboutnum1")));
$("#aboutContentDiv").append($("<div></div>").load("Home/About/" + $(this).attr("aboutnum2")));
});
</script>
The Following is my Comtroller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestApp.MyObjects;
namespace TestApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
Contact c = new Contact();
c.name = "Some Name";
c.someValues = new List<string>();
c.someValues.Add("1");
c.someValues.Add("2");
c.someValues.Add("3");
Contact c1 = new Contact();
c1.name = "Some Name1";
c1.someValues = new List<string>();
c1.someValues.Add("4");
c1.someValues.Add("5");
c1.someValues.Add("6");
Contact c2 = new Contact();
c2.name = "Some Name2";
c2.someValues = new List<string>();
c2.someValues.Add("7");
c2.someValues.Add("8");
c2.someValues.Add("9");
List<Contact> clist = new List<Contact>();
clist.Add(c);
clist.Add(c1);
clist.Add(c2);
Session["myCoolValue"] = "Cool1";
TempData["myCoolValue"] = "Cool2";
return View(clist);
}
[HttpPost]
public ActionResult Index(List<Contact> contacts)
{
string name = contacts[0].name;
return View("Index",contacts);
}
public PartialViewResult About(string id = "")
{
ViewBag.Message = "Your app description page.";
About a = new About();
a.someValue = id + " _ modified by contoller";
ViewBag.myCoolValue = "Cool";
return PartialView("About",a);
}
public PartialViewResult Contact()
{
ViewBag.Message = "Your contact page.";
return PartialView("Contact");
}
}
}
Based on your reply to my comment, you need something like this:
// you can use foreach and have a counter variable or this
for (int i = 0; i < Model.Count; i++)
{
// you do not want to use a partial view so let's do it this way
// put this in an appropriate place in your code
// like inside a tr or div, it's up to you
#Html.TextboxFor(m => m[i].name)
}