Downloading File in ASP.NET Core MVC - asp.net-core

Completely new on .Net core from MVC5, so how does download file works with .NET Core? I have tried writing down code but it has errors. Thanks in advance to the helpers.
Controller
public ActionResult Download()
{
string[] files = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
for (int i = 0; i < files.Length; i++)
{
files[i] = Path.GetFileName(files[i]);
}
ViewBag.Files = files;
return View();
}
public FileResult DownloadFile(string fileName)
{
var filepath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
return File(filepath, LineMapping.GetMimeMapping(filepath), fileName);
}
View
<h2>Downloads</h2>
<table>
<tr>
<th>File Name</th>
<th>Link</th>
</tr>
#for (var i =0; i <= Model.Count -1; i++) {
<tr>
<td>
#Model[i].ToString()
</td>
<td>
#Html.ActionLink("Download", "Download", new { ImageName=#Model[i].ToString() })
</td>
</tr>
}

The code as written will not even compile because Path.Combine does not return a list of files. You will also get parsing errors in your view because you reference Model but you don't have a model. Also, your parameter ImageName doesn't match your action's parameter name. Several other issues with the code too (using Count on an array - use Count() or Length.
I think you are trying to do something like this?
Controller
public ActionResult Download()
{
string[] files = Directory.GetFiles(Path.Combine(_hostingEnvironment.WebRootPath, "uploads"));
for (int i = 0; i < files.Length; i++)
{
files[i] = Path.GetFileName(files[i]);
}
return View(files);
}
public FileResult DownloadFile(string fileName)
{
var filepath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads", fileName);
return File(filepath, "application/pdf", fileName);
}
View
<table>
<tr>
<th>File Name</th>
<th>Link</th>
</tr>
#for (var i = 0; i <= Model.Length - 1; i++)
{
<tr>
<td>
#Model[i].ToString()
</td>
<td>
#Html.ActionLink("Download", "DownloadFile", new { fileName = #Model[i].ToString() })
</td>
</tr>
}
</table>

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>

Why session.getAttribute() always returning null inside JSP page textbox?

I am always getting null value in jsp page textbox. I have defined name attribute in index.jsp page and fetching value using <%=session.getAttribute()%>.
Here is index.jsp
<tr>
<td>First Name</td>
<td>
<input type="text" required="" name="firstname" value="<%=session.getAttribute("firstname")%>"/>
</td>
</tr>
In below UploadServletClass.java, session is defined
public class UploadServletClass extends HttpServlet{
PrintWriter out = null;
Connection con = null;
PreparedStatement ps = null;
HttpSession session = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/plain;charset=UTF-8");
try{
out = response.getWriter();
session = request.getSession();
...
}
}
}
This is loginScript.jsp
<%
String zfid = request.getParameter("zid");
String fname = request.getParameter("firstname");
...
if (rs.next()) {
session.setAttribute("zfid", zfid); //used ${sessionScope.zfid} to display value into textbox and it is successful.
session.setAttribute("firstname",fname); //failed to display value in textbox
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("home.jsp");
}

how to get data by Id and view bag to view MVC

i have View Named Index i want to pass data get by GuidId. in Model and View Bag ... after enter Id how do this
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> GetDS(Guid Id)
{
var url = string.Empty;
url = ApiEndpoint.serviceUrl + ApiEndpoint.GetDS + Id;
var data = await ApiService.GetAsync<DSModel>(url).ConfigureAwait(false);
url = ApiEndpoint.serviceUrl + ApiEndpoint.GetDSL + Id;
var data2 = await ApiService.GetAsyncCollection<DSLDetails>(url).ConfigureAwait(false);
ViewBag.DSL = data2;
return View("Index", data);
}
html error shows in HTML Side
#foreach (var item in #ViewBag.DSL)
{
<tr>
<td>
#item.Name
</td>
}
ERROR NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Division_Index.ExecuteAsync() in Index.cshtml
+
#foreach (var item in #ViewBag.DSL)
You are getting this exception because #ViewBag.DSL is null in foreach loop. Please make sure that you are storing data in viewbag from server side in action menthod.
And second thing try this code:
#if(ViewBag.DSL != null)
{
foreach (var item in ViewBag.DSL)
{
<tr>
<td>
#item.Name
</td>
</tr>
}
}

Sharepoint 2013 - FBA and 2FA with custom login page

I'm a complete noob in Sharepoint. I've just started learning sharepoint 2 weeks ago coz my boss assigned me to a sharepoint project. I have to implement 2FA and FBA in an existing claims based intranet web application. I though it would be a simple task to do just by researching but I haven't found a clear guide or answer for my question.
Here are a few of my tasks:
1) Add forms based authentication to the site and use custom login page.
2) Authentication
Check user's name and password with AD upon login.
If valid, have to request OTP code from the 3rd party provider for
2FA.
User is authenticated after passing both.
Configurations and custom login page were not much trouble and it didn't take long to get them done. But I'm stuck at the 2FA part.
1) How to customize the authentication process? I don't remember where did I get the below code but I really hoped that I would be able to do something with it. So, can I do something with it or I'm going the wrong path? I'd really appreciate any help and thanks a lot in advance.
protected void btnLogin_Click(object sender, EventArgs e)
{
bool status = SPClaimsUtility.AuthenticateFormsUser(
Context.Request.UrlReferrer,
txtUsername.Value.ToString(),
txtPassword.Value.ToString());
if (!status) // if auth failed
{
lblInvalid.InnerText = "Wrong Username or Password";
lblInvalid.Visible = true;
}
else //if success
{
//What do I do here to change the user back to not authenticated?
}
}
After you properly log in set federated authentication cookie domain.
HttpCookie httpCookie = current.Response.Cookies["FedAuth"];
httpCookie.Domain = "." + ConfigurationManager.AppSettings["yourdomain"];
Sign out method is more complicated, long time ago i based my solution on this post
And sign out method (sorry for variable names but i'm decompiling my old dll) based on sharepoint SignOut page and fix from the post:
public static void SignOut(SPSite site, SPWeb web, IClaimsPrincipal principal)
{
HttpContext current = HttpContext.Current;
if (current.Session != null)
{
current.Session.Clear();
}
string value = string.Empty;
if (current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
{
value = "NoCookie";
}
HttpCookie httpCookie = current.Request.Cookies["WSS_KeepSessionAuthenticated"];
bool flag = false;
for (int i = 0; i < current.Request.Cookies.Count; i++)
{
HttpCookie httpCookie2 = current.Request.Cookies.Get(i);
if (httpCookie2.Name == "FedAuth" && !flag)
{
flag = true;
httpCookie2.Domain = WebConfigurationManager.AppSettings["yourdomain"];
}
}
if (httpCookie != null)
{
httpCookie.Value = value;
current.Response.Cookies.Remove("WSS_KeepSessionAuthenticated");
current.Response.Cookies.Add(httpCookie);
}
HttpCookie httpCookie3 = current.Request.Cookies["MSOWebPartPage_AnonymousAccessCookie"];
if (httpCookie3 != null)
{
httpCookie3.Value = value;
httpCookie3.Expires = new DateTime(1970, 1, 1);
current.Response.Cookies.Remove("MSOWebPartPage_AnonymousAccessCookie");
current.Response.Cookies.Add(httpCookie3);
}
SPIisSettings iisSettingsWithFallback = site.WebApplication.GetIisSettingsWithFallback(site.Zone);
if (iisSettingsWithFallback.UseClaimsAuthentication)
{
string iPUrl = Authentication.GetIPUrl(principal);
if (iPUrl != string.Empty)
{
string str = HttpUtility.UrlEncode(SPContext.Current.Site.RootWeb.Url);
string url = iPUrl + "?wa=wsignout1.0&wreply=" + str;
FederatedAuthentication.SessionAuthenticationModule.SignOut();
if (current.Session != null)
{
current.Session.Abandon();
}
current.Response.Redirect(url);
}
else
{
FederatedAuthentication.SessionAuthenticationModule.SignOut();
int num = 0;
foreach (SPAuthenticationProvider current2 in iisSettingsWithFallback.ClaimsAuthenticationProviders)
{
num++;
}
if (num != 1 || !iisSettingsWithFallback.UseWindowsIntegratedAuthentication)
{
if (current.Session != null)
{
current.Session.Abandon();
}
SPUtility.Redirect(web.ServerRelativeUrl, 0, current);
return;
}
}
}
if (AuthenticationMode.Forms == SPSecurity.AuthenticationMode)
{
FormsAuthentication.SignOut();
if (current.Session != null)
{
current.Session.Abandon();
}
SPUtility.Redirect(web.ServerRelativeUrl, 0, current);
}
else if (AuthenticationMode.Windows != SPSecurity.AuthenticationMode)
{
throw new SPException();
}
}
private static string GetIPUrl(IClaimsPrincipal principal)
{
string result;
if (principal == null)
{
result = string.Empty;
}
else
{
string text = string.Empty;
try
{
string text2 = principal.Identity.Name.Split(new char[] {'|'})[1];
if (SPSecurityTokenServiceManager.Local.TrustedLoginProviders[text2] != null)
{
text = SPSecurityTokenServiceManager.Local.TrustedLoginProviders[text2].ProviderUri.AbsoluteUri;
}
}
catch (Exception ex)
{
// log
}
result = text;
}
return result;
}
Further reading:
Writing A Custom Forms Login Page for SharePoint 2010
Custom Single Sign-On Scenario in SharePoint 2010
Normal aspx page
<html>
<head>One Head</head>
<body>
<form runat="server">
<table>
<tr>
<td>User Name:</td>
<td>
<asp:TextBox ID="txtUserName" runat="server" /></td>
</tr>
<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="txtPassword" TextMode="Password" runat="server" /></td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnButton" Text="Button" OnClick="btnButton_Click" runat="server" />
</td>
</tr>
</table>
</form>
</body>
</html>
You may have trouble in adding Microsoft.SharePoint.identityModel, here is the location I got
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\v4.0_15.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.IdentityModel.dll
List of Includes
using System;
using Microsoft.SharePoint;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using Microsoft.SharePoint.IdentityModel;
using System.IdentityModel.Tokens;
Button click code
protected void btnButton_Click(object sender, EventArgs e)
{
string domn = "mydomain";
string membershipProviderName = "membership";
string roleProviderName = "rolemanager";
string cookieeee = string.Format("{0}\\{1}", domn, txtUserName.Text);
bool isAuthenticated = Authenticate(domn, txtUserName.Text, txtPassword.Text);
if (isAuthenticated)
{
SecurityToken token = SPSecurityContext.SecurityTokenForFormsAuthentication(new Uri(SPContext.Current.Web.Url),
membershipProviderName, roleProviderName, txtUserName.Text, txtPassword.Text,
SPFormsAuthenticationOption.PersistentSignInRequest);
SPFederationAuthenticationModule.Current.SetPrincipalAndWriteSessionToken(token);
Response.Redirect("/");
}
}
[DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted = true)]
public static bool Authenticate(string domainName, string userAlias, string userPassword)
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName);
return context.ValidateCredentials(userAlias, userPassword, ContextOptions.Negotiate));
}
catch
{
throw;
}
}
Note: Make sure you have all FBA configurations set in web config files. This is only custom authentication this will not work if role and membership are not set properly in the central admin and web config on services and webapplication.

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)
}