Create User by profession - How to Populate/Submit/Validate form? - asp.net-mvc

I am trying to create user by registration form which contains dropdown for profession in ASP.NET MVC
Eg. Individual, professional, manager etc.
some fields are common like name & Last Name...
some fields are unique by profession...
how do i program it with ajax.
Thanks

I do this sort of thing by creating a SelectList in a controller and passing it to the view as part of a view model. Then in the view, I have the option of doing something when the SelectedValue changes, or simply returning the value of the dropdown when something else triggers a call to a controller.
Controller code:
int count = 0;
List<string> YearList = new List<string>();
for (int i = 2000; i < (DateTime.Now.Year + 6); i += 4)
{
YearList.Add(i.ToString());
if (i < iyear)
count++;
}
var q = from c in doc.Descendants("candidate")
select new can_sw_model
{
name = c.Attribute("name").Value,
office = c.Parent.Attribute("name").Value.ToUpper(),
party = c.Attribute("party").Value,
};
can_sw_view model = new can_sw_view()
{
YearList = new SelectList(YearList),
value = YearList[count],
model = q,
};
return View(model);
View code:
<script type="text/javascript">
$(document).ready(function() {
$('#YearList').val('<%= Model.value %>');
$('#YearList').change(function(event) {
window.location.replace('<%= ResolveUrl("~/Candidate/sw_candidates") %>' + "?year=" + $('#YearList').val());
});
});
function pdfclick() {
var grid = $("#grid1").data("tGrid");
window.location.replace('<%= ResolveUrl("~/Candidate/pdf") %>' + "?year=" + $('#YearList').val() + "&tab=statewide" +
"&page=" + grid.currentPage + "&orderBy=" + grid.orderBy + "&groupBy=" + grid.groupBy + "&filterBy=" + grid.filterBy);
}
</script>
I hope this helps!
Bob

Related

ASP.NET MVC 5 Edit and Create Separate

public ActionResult NewLine(int index, ExpenseLine newLine)
{
newLine.Indis = index;
List<ExpenseLine> expenses;
if (Session["ExpenseLines"] == null)
{
expenses = new List<ExpenseLine>();
}
else
{
expenses = (List<ExpenseLine>)Session["ExpenseLines"];
var OldExpense = expenses.Where(x => x.IndexNo == index).FirstOrDefault();
newLine.Key = OldExpense.Key;
}
var model = SetVariables(new Expense() { ExpenseLines = new List<ExpenseLine> { newLine } });
newLine.IndexNo = expenses.Count + 1;
var exp = expenses.Where(x => x.Indis == newLine.Indis).ToList();
foreach (var item in exp)
{
expenses.Remove(item);
}
expenses.Add(newLine);
Session["ExpenseLines"] = expenses;
return PartialView("~/Views/Expense/EditorTemplates/ExpenseLine.cshtml", model.ExpenseLines.First());
}
I have a expense modal in cshtml.
There is a button. The part where I press the button both adds a row and edits the modal if it is not empty. When I press save, it goes to the above action and the row I just added deletes it because it takes the key of the old row. I don't do it like that. The distinguishing feature is only key.index and others do not affect the action. If I'm adding a new line, I don't want it to enter the "else" part. How can I do it ?

Umbraco count active content pages

I would like to get a count of pages in nodes in an Umbraco site with output something like this:
Root (9 subnodes)
First Folder (4 subnodes)
document 1
document 2
document 3
document 4
Second Folder (3 subnodes)
document 1
document 2
document 3
Basically I am trying to see how much active content there is in a given site and come up with a way to divide the work. Is there a reasonable way to get this information?
This worked for me:
Descendants.cs in App_Code folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.presentation;
using umbraco.presentation.nodeFactory;
public static class ExtensionMethods
{
public static IEnumerable<Node> AllDescendants(this Node node)
{
foreach (Node child in node.Children)
{
yield return child;
foreach (Node grandChild in child.AllDescendants())
yield return grandChild;
}
}
}
Razor View
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#using umbraco.presentation.nodeFactory;
#{
Layout = "";
}
#functions{
public string CreateSitemap()
{
var temp = "<ul class='collapsibleList'>" + sitemap(-1) + "</ul>" + Environment.NewLine;
return temp;
}
public string sitemap(int nodeID)
{
var rootNode = new umbraco.presentation.nodeFactory.Node(nodeID);
var sitemapstring = "<li>" + rootNode.Name + " (" + rootNode.AllDescendants().Count() + ") <span style='font-size:9px'>" + rootNode.NodeTypeAlias + "</span></li>" + Environment.NewLine;
if (rootNode.Children.Count > 0)
{
sitemapstring += "<ul>" + Environment.NewLine;
sitemapstring = rootNode.Children.Cast<Node>().Aggregate(sitemapstring, (current, node) => current + sitemap(node.Id));
sitemapstring += "</ul>" + Environment.NewLine;
}
return sitemapstring;
}
}
<body>
#Html.Raw(CreateSitemap())
</body>

dynamic dataset in stimulsof with asp.net mvc

I use stimulsoft in asp.net mvc for reporting ...
I want to bind a dynamic datatable/dataset into my report , So I search for it and
There is my code
View:
#Html.StiMvcViewerFx(new StiMvcViewerFxOptions()
{
ActionGetReportSnapshot = "GetReportSnapshot",
Width = Unit.Percentage(100),
Height = Unit.Pixel(700),
Zoom = 100
})
Controller:
public ActionResult GetReportSnapshot()
{
var report = new StiReport();
//a blank file .mrt
report.Load( Server.MapPath("~") + "Content/StimulReport/Data/Surveys/Report/Report.mrt" );
var dt = new DataTable("Text");
dt.Columns.Add("Name");
for (int i = 0; i < 100; i++)
{
dt.Rows.Add(i);
}
var dataSet = new DataSet("Demo");
dataSet.Tables.Add(dt);
report.RegData(dataSet);
return StiMvcViewerFxHelper.GetReportSnapshotResult(report);
}
But the Report Just Show A Blank Page:
For windows application it's work correctly but in web it's not
Please help me
Try to use next code:
report.RegData(dataSet);
return StiMvcViewerFxHelper.GetReportSnapshotResult(this.Request, report);

breezejs: overriding displayname

I'm in the process of customizing validation messages. It's working fine using the messageTemplates property. However it uses %displayName% to render the name of the property and I can't find out how to override this value ? Is there anyway to do that ?
I was wanting to do this also but I wanted to use the [DisplayName] attribute from my EF model. I couldn't find anyone that had an example of doing this so after I found a way I thought I would share.
First, I extended the metadata returned from my BreezeController:
[HttpGet]
public string Metadata()
{
// Extend metadata with extra attributes
JObject metadata = JObject.Parse(contextProvider.Metadata());
string nameSpace = metadata["schema"]["namespace"].ToString();
foreach (var entityType in metadata["schema"]["entityType"])
{
string typeName = entityType["name"].ToString();
Type t = Type.GetType(nameSpace + "." + typeName);
foreach (var prop in t.GetProperties())
{
foreach (var attr in prop.CustomAttributes)
{
string name = attr.GetType().Name;
foreach (var p in entityType["property"])
{
if (prop.Name == p["name"].ToString()) {
if (attr.AttributeType.Name == "DisplayNameAttribute") {
DisplayNameAttribute a = (DisplayNameAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayNameAttribute));
p["displayName"] = a.DisplayName;
break;
}
}
}
}
}
}
return metadata.ToString();
}
Then I added a little javascript after the metadata load to poke the display names from the augmented metadata where Breeze wants to find them.
manager.fetchMetadata().then(function (md) {
angular.forEach(md.schema.entityType, function (et) {
var etype = manager.metadataStore.getEntityType(et.name);
angular.forEach(et.property, function (p) {
var prop = etype.getProperty(p.name);
prop.displayName = p.displayName;
});
});
console.log("starting app");
angular.bootstrap($("#app"), ["app"]);
});
I'm using angular so if you aren't you can ignore the angular stuff and probably get the idea. This seems to work rather nicely. It should be pretty easy to extend this to other model attributes as well like the RegularExpression validation attribute. I'll probably work on that next.
FYI, some of this code is not optimized and could probably be refactored, prettied up a bit but I just got it working and thought I would share. If anyone has any suggestions of a better way let me know. Hopefully Breeze will allow extending the metadata in a more supported way in the future. This does seem like a bit of a hack.
This is not YET well documented but you can simply set the 'displayName' property on any dataProperty and this will override the autogenerated display name and will be used for all validation messages for this property. So
var custType = myEntityManager.metadataStore.getEntityType("Customer");
var dp = custType.getProperty("companyName");
dp.displayName = "My custom display name";
Also, please see "Customize the message templates" at the bottom of this page: Breeze Validation
Following jpcoder request for suggestions, here goes my slightly improved server portion:
JObject metadata = JObject.Parse(contextProvider.Metadata());
string nameSpace = metadata["schema"]["namespace"].ToString();
foreach (var entityType in metadata["schema"]["entityType"])
{
string typeName = entityType["name"].ToString();
Type t = Type.GetType(nameSpace + "." + typeName);
IEnumerable<JToken> metaProps = null;
if (entityType["property"].Type == JTokenType.Object)
metaProps = new[] { entityType["property"] };
else
metaProps = entityType["property"].AsEnumerable();
var props = from p in metaProps
let pname = p["name"].ToString()
let prop = t.GetProperties().SingleOrDefault(prop => prop.Name == pname)
where prop != null
from attr in prop.CustomAttributes
where attr.AttributeType.Name == "DisplayNameAttribute"
select new
{
Prop = p,
DisplayName = ((DisplayNameAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayNameAttribute))).DisplayName
};
foreach (var p in props)
p.Prop["displayName"] = p.DisplayName;
}
Looking at http://www.breezejs.com/sites/all/apidocs/files/a40_entityMetadata.js.html#l1452,
could this be improved by renaming the existing "name" value to nameOnServer (to satisfy the getDataProperty call) and inserting the DisplayNameAttribute value as "name"?
A necessary change to the server code is that, if your model classes are in different assemblies, you cannot use
Type t = Type.GetType(nameSpace + "." + typeName);
You need the namespace per type (which is in the metadata), and (I think) to use BuildManager to locate the appropriate types in different assemblies. The mapping from cSpaceOSpaceMapping might be achieved more elegantly, but I didn't have time to research the different json formatting options.
JObject metadata = JObject.Parse(UnitOfWork.Metadata());
string EFNameSpace = metadata["schema"]["namespace"].ToString();
string typeNameSpaces = metadata["schema"]["cSpaceOSpaceMapping"].ToString();
typeNameSpaces = "{" + typeNameSpaces.Replace("],[", "]|[").Replace("[", "").Replace("]", "").Replace(",", ":").Replace("|", ",") + "}";
JObject jTypeNameSpaces = JObject.Parse(typeNameSpaces);
foreach (var entityType in metadata["schema"]["entityType"])
{
string typeName = entityType["name"].ToString();
string defaultTypeNameSpace = EFNameSpace + "." + typeName;
string entityTypeNameSpace = jTypeNameSpaces[defaultTypeNameSpace].ToString();
Type t = BuildManager.GetType(entityTypeNameSpace, false);
IEnumerable<JToken> metaProps = null;
if (entityType["property"].Type == JTokenType.Object)
metaProps = new[] { entityType["property"] };
else
metaProps = entityType["property"].AsEnumerable();
var props = from p in metaProps
let pname = p["name"].ToString()
let prop = t.GetProperties().SingleOrDefault(prop => prop.Name == pname)
where prop != null
from attr in prop.CustomAttributes
where attr.AttributeType.Name == "DisplayNameAttribute"
select new
{
Prop = p,
DisplayName = ((DisplayNameAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayNameAttribute))).DisplayName
};
foreach (var p in props)
{
p.Prop["displayName"] = p.DisplayName;
}
}
JObject metadata = JObject.Parse(this._context.Metadata());
string EFNameSpace = metadata["schema"]["namespace"].ToString();
string typeNameSpaces = metadata["schema"]["cSpaceOSpaceMapping"].ToString();
typeNameSpaces = "{" + typeNameSpaces.Replace("],[", "]|[").Replace("[", "").Replace("]", "").Replace(",", ":").Replace("|", ",") + "}";
JObject jTypeNameSpaces = JObject.Parse(typeNameSpaces);
foreach (var entityType in metadata["schema"]["entityType"])
{
string typeName = entityType["name"].ToString();
string defaultTypeNameSpace = EFNameSpace + "." + typeName;
string entityTypeNameSpace = jTypeNameSpaces[defaultTypeNameSpace].ToString();
Type t = BuildManager.GetType(entityTypeNameSpace, false);
IEnumerable<JToken> metaProps = null;
if (entityType["property"].Type == JTokenType.Object)
metaProps = new[] { entityType["property"] };
else
metaProps = entityType["property"].AsEnumerable();
var props = from p in metaProps
let pname = p["name"].ToString()
let prop = t.GetProperties().SingleOrDefault(prop => prop.Name == pname)
where prop != null
from attr in prop.CustomAttributes
where attr.AttributeType.Name == "DisplayAttribute"
select new
{
Prop = p,
DisplayName = ((DisplayAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayAttribute))).Name
};
foreach (var p in props)
{
p.Prop["displayName"] = p.DisplayName;
}
}
return metadata.ToString();
Improving jpcoder's answer ...
For me most of my DisplayName changes were to replace "PascalCaseFieldName" or "camelCaseFieldName" with "Upper Case Field Name". So rather than set every property DisplayName on the server, I applied a default function to set displayName.
End result was much less EF annotation required. My TypeScript is:
manager.metadataStore.getEntityTypes().forEach(function (storeEntityType) {
if (!(storeEntityType instanceof breeze.EntityType)) {
throw new Error("loadExtendedMetadata found '" + storeEntityType
+ "' StructuralType that is not an EntityType (e.g. a ComplexType)");
}
var extEntityType = extendedMetadata.entitiesExtended.find((extendedEntityType) => {
return extendedEntityType.shortName + ":#" + extendedEntityType.nameSpace === storeEntityType.name;
});
(storeEntityType as breeze.EntityType).getProperties().forEach((storeProperty) => {
//Both NavigationProperty & DataProperty have displayName & nameOnServer properties
var storeDataProperty = <breeze.DataProperty>storeProperty;
var extProperty;
if (extEntityType) {
extProperty = extEntityType.propertiesExtented.find((extendedProperty) => {
return extendedProperty.name === storeDataProperty.nameOnServer;
});
}
//Smart default: nameOnServer "PascalCaseFieldName" or "camelCaseFieldName" converted to "Upper Case Field Name"
storeDataProperty.displayName = (extProperty && extProperty.displayName)
|| storeDataProperty.nameOnServer.replace(/^./, function (str) {
// first ensure the first character is uppercase
return str.toUpperCase();
// insert a space before all caps, remove first character (added space)
}).replace(/([A-Z])/g, " $1").substring(1);
});
});

ASP.NET MVC Function that returns a model

I've a model that includes some data, but when the modelstate isn't valid it needs to fill up the model again. So i have to fill multiple times my model. So i would like to make a function that returns the model for me, so i can use it in my controller. How can i achieve this?
Thanks for reading.
I simply tried to make a public string.
This is my code:
public string LaadGastenboek(int id)
{
Models.Berichten Gastenboek = new Models.Berichten();
Models.Gastenboekmaken Gastenboekberichtmaken = new Models.Gastenboekmaken();
int hoeveelzoudenermoetenzijn = id * 10 - 9;
if (SQL.ReturnSingleINTResult("Select count(*) from Gastenboek where status = 1") >= hoeveelzoudenermoetenzijn)
{
String Gastenboekunsorted = SQL.LaadGastenboek(hoeveelzoudenermoetenzijn);
// Gastenboek data -- Properties
int tellerhtml = 1;
int teller = 1;
// Array
if (Gastenboekunsorted != null)
{
string[] ArrayGastenboek = Gastenboekunsorted.Split('*');
// Split alles, 1 bericht is 3 data
for (int nummer = 0; ArrayGastenboek.Count() > nummer - 1; nummer++)
{
if (tellerhtml == 3)
{
Models.GastenBoekBerichtenModel item = new Models.GastenBoekBerichtenModel();
// Bereken het verschil, - 4 omdat hij begint te tellen bij 0
tellerhtml = teller - 4;
// Zet t/m 3 van arraygastenboek in de html code
// Bericht - Naam - Datum
item.Bericht = ArrayGastenboek[tellerhtml + 1];
item.Naam = ArrayGastenboek[tellerhtml + 2];
item.Datum = ArrayGastenboek[tellerhtml + 3];
Gastenboek.Add(item);
// Reset
tellerhtml = 0;
}
teller++;
tellerhtml++;
}
}
}
return (new Models.GastenboekOverall(Gastenboek, Gastenboekberichtmaken));
}
From your comment:
"The question is how i can modify my code that it returns a model."
I assume you want to modify your code to return model.
public Models.GastenboekOverall LaadGastenboek(int id)
{
... your code here ...
return (new Models.GastenboekOverall(Gastenboek, Gastenboekberichtmaken));
}
In your controller to pass the model into view you can write, assuming your view consume model Models.GastenboekOverall.
public ActionResult Index()
{
return view (LaadGastenboek(someId));
}

Resources