Trying to understand how to submit a form - c#

I'm currently working on an "Activity Report" application on a first year internship, where employees can select a specific project and assign how many hours they have worked on it per day.
The selection of projects (depending on the employees id) and the display of the page seem to be working. But here's my problem : once I click on the displayed image that is supposed to submit the form - it seems to reload the page as if nothing happened !
The View line of the submission is as following :
<% using (Html.BeginForm("ActivityInputCreate", "Project"))
{ %>
[...]
<td>
<input type="image" style="border: 0; width: 16px;" src="../../Content/Black_16x16/Save.png" onclick="this.form.submit" alt="save" />
<input type="image" style="border: 0; width: 16px;" src="../../Content/Black_16x16/Cancel.png" onclick=" window.location.href = '/Project/ActivityInputIndex'; return false;" alt="cancel" /></td>
<!-- the first line being to save and the second to cancel -->
<td>
}
I don't know how to handle a form submission but here's the controller (the first of the same name being the non [HttpPost] one :
[HttpPost]
public ActionResult ActivityInputCreate(Project objToCreate, FormCollection form)
{
string year = form["Years"];
int iyear = int.Parse(year);
string month = form["Months"];
int imonth = int.Parse(month);
string strUser = Environment.UserName.ToLower();
CalendarController c = new CalendarController();
ViewBag.ListYears = c.ListYears(iyear);
ViewBag.ListMonths = c.ListMonths(imonth);
ViewBag.ListDaysOfMonth = _service.ListDaysOfMonth(iyear.ToString(), imonth.ToString());
//nea11
Session["ActivityInputYear"] = iyear.ToString();
Session["ActivityInputMonth"] = imonth.ToString();
ProjectResourceManagerService pr = new ProjectResourceManagerService(new ModelStateWrapper(this.ModelState));
ViewBag.ProjectList = pr.ListProject();
List<IEnumerable<SelectListItem>> ddlists = new List<IEnumerable<SelectListItem>>();
foreach (string s in ViewBag.ListDaysOfMonth)
ddlists.Add(_service.ListHours(0)); //id de UserActivity à la place de 0
ViewBag.ddlists = ddlists;
//nea12
string strProject = form["Project"];
//nea13
string strSep = ";";
string strDatas = "";
int l = 0;
foreach (var jour in ViewBag.ListDaysOfMonth)
{
string nom = "Hours" + l.ToString();
strDatas += form[nom] + strSep;
l++;
}
//ajout dans la base
UserActivityDb db = new UserActivityDb(#"metadata=res://*/Models.CRA.csdl|res://*/Models.CRA.ssdl|res://*/Models.CRA.msl;provider=Microsoft OLE DB Provider for SQL server;provider connection string="data source=(local)\SQLEXPRESS;initial catalog=CRAV34;persist security info=True;user id=sa;password=as0;multipleactiveresultsets=True;App=EntityFramework"");
if (null != strProject)
db.setFormattedData(iyear, imonth, ViewBag.ListDaysOfMonth, int.Parse(strProject), strUser, strDatas, true);
IEnumerable<Project> lp = _service.List(strUser, iyear.ToString(), imonth.ToString());
lp = lp.Where(p => (true == db.ExistUserActivity(iyear, imonth, ViewBag.ListDaysOfMonth, p.ProjectId, strUser)));
//nea35
List<string[]> lstInts = new List<string[]>();
foreach (Project p in lp)
{
string strInts = db.getFormattedData(iyear, imonth, ViewBag.ListDaysOfMonth, p.ProjectId, strUser, null, 0);
string[] ints = strInts.Split(';');
lstInts.Add(ints);
}
ViewBag.ProjectInts = lstInts;
return View("ActivityInputIndex", lp);
}
I'd love to give you more precision but please keep in mind that most of the code isn't mine and is the last interns'.
TL;DR : Display of the page is fine, I want to submit once the DropDownList are filled, submission button doesn't do anything.
Thank you.

Turns out the issue came with the input of my username (through the SQL INSERT).
string strUser = User.Identity.Name;
Is used with :
command.Parameters.Add("#Login", SqlDbType.VarChar, 50).Value = sLogin;
And works just fine. The issue was not with the sending of a form (which it did receive) but the way the SQL request was built.

Related

Search through MVC search results

I have an MVC site that is connected to a database with multiple tables. Some of the tables have only 1000 or so records, so searching through those is fairly simple. However, one of the tables has over 2 million records, and I tried implementing the same searching method but it is far too slow. For the tables with less records, the search goes through every column looking for matches, but the table with a million records can only search through one column in an efficient manner. Essentially, what I want to do to fix this problem is to allow the user to search through the search results. So if I were to search by apple in the table with a million records, let's say that 100,000 records remain. Then, I could search by Gala on the remaining 100,000 records to narrow the results down even more. Is this possible? Or is there possibly a better way to search through this many records that I am not thinking of?
Controller
public ViewResult Index(string sortOrder, string currentFilter, string search, int? page, int? pageSize)
{
int pageIndex = 1;
pageIndex = page.HasValue? Convert.ToInt32(page) : 1;
int defaSize = (pageSize ?? 25);
ViewBag.psize = defaSize;
ViewBag.PageSize = new List<SelectListItem>()
{
new SelectListItem() { Value = "25",Text = "25"},
new SelectListItem() { Value = "50",Text = "50"},
new SelectListItem() { Value = "100",Text = "100"},
new SelectListItem() { Value = "1000",Text = "1000"},
};
ViewData["ControllerName"] = this.ToString();
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "pkDeviceUnderTest" : "";
if (search == null)
{
ViewBag.TotalCount = dbModel.DeviceUnderTests.Count();
}
else
{
var ld = dbModel.DeviceUnderTests.Where(x => x.nkDeviceUnderTest.Contains(search)||x.nkNotes.Contains(search)||x.FaultApplication.nkFaultApplication.Contains(search)||x.Firmware.nkFirmware.Contains(search)
||x.Hardware.nkHardware.Contains(search)||x.Location.nkLocation.Contains(search)||x.Power.nkPower.Contains(search)||x.nkHandleRating.ToString().Contains(search)||x.nkPreEventTime.ToString().Contains(search)).ToList()
.Count();
ViewBag.TotalCount = ld;
}
ViewBag.cf = currentFilter;
ViewBag.search = search;
Session["searchcircuit"] = search;
ViewBag.defaSize = defaSize;
var div = ViewBag.TotalCount / defaSize;
ViewBag.numofPages = ((ViewBag.defaSize - 1) + ViewBag.TotalCount) / ViewBag.defaSize;
ViewBag.index = pageIndex;
int pagenum = pageIndex;
var records = dbModel.DeviceUnderTests.Where(x => x.nkDeviceUnderTest.Contains(search) || x.nkNotes.Contains(search) || x.FaultApplication.nkFaultApplication.Contains(search) || x.Firmware.nkFirmware.Contains(search)
|| x.Hardware.nkHardware.Contains(search) || x.Location.nkLocation.Contains(search) || x.Power.nkPower.Contains(search) || x.nkHandleRating.ToString().Contains(search) ||search==null|| x.nkPreEventTime.ToString().Contains(search)).OrderBy(x => x.pkDeviceUnderTest).Skip(defaSize * (pagenum - 1)).Take(defaSize);
var result = new StaticPagedList<DeviceUnderTest>(records, pageIndex, defaSize, ViewBag.TotalCount);
return View(result);
}
View
#using (Html.BeginForm("Index", "Circuit", FormMethod.Get))
{
<input type="text" name="search" placeholder="Search ... " />
<input type="submit" name="submit" value="Search" class="btn btn-default" style="background-color:#337ab7;color:azure" />
}

PartialView(); The name does not exist in the current context

So im a bit stuck. I'm still learning all this stuff., but I had to add a csv parser to my application, which should display the results on the my alerts page. If I do
return PartialView(model, pin, tDate, stat);
It will tell me pin, tDate and stat does not exist in the current context. If I take them out, the app will run, but doesn't display the intended result.
I declared pin, tDate and stat in the UserADInfoModel.cs
here is the controller:
public ActionResult _Alerts(UserADInfoModel model, List<string> groups)
{
DataRowCollection drColl = Core.GetAlerts(model);
ViewBag.Alerts = drColl;
var path = #"Exchange Migration data 10-25-17.csv";
using (TextFieldParser csvParser = new TextFieldParser(path))
{
csvParser.CommentTokens = new string[] { "#" };
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvParser.ReadLine();
// Read the lines
while (!csvParser.EndOfData)
{
string[] fields = csvParser.ReadFields();
string pin = fields[0];
string tDate = fields[2];
string stat = fields[6];
}
}
return PartialView(model, pin, tDate, stat);
}
and here is the view
#if (#ViewBag.pin == Model.SAM)
{
<tr style="background-color : #ff3333; color: #ffffff">
<td style="padding-left :10px; padding-right: 10px;padding-top:2px; padding-bottom: 2px">
<p>Critical</p>
</td>
<td style="padding-left :10px; padding-right: 10px;padding-top:2px; padding-bottom: 2px">
<p>Exchange Migration</p>
</td>
<td style="padding-left :10px; padding-right: 10px;padding-top:2px; padding-bottom: 2px">
<p>Caller was set to migrate on (#ViewBag.tDate). The status of the migration is (#ViewBag.stat). Please contact Hypercare</p>
</td>
</tr>
}
#foreach (var x in ViewBag.Alerts)
{
var uClass = (x["Weight"].Contains("Warning")) ? "#ff8c1a, " : (x["Weight"].Contains("Critical")) ? "#ff3333" : "";
<tr #if (x["Weight"].Contains("Warning")) {
#MvcHtmlString.Create("style=\"background-color: #ff8c1a\"")
}
else if(x["Weight"].Contains("Critical")){
#MvcHtmlString.Create("style=\"background-color: #ff3333; color: #ffffff\"")
}>
what am I doing wrong? TIA
You declared pin, tDate and stat inside the while scope.
Decide if you want to use model (recommended) or ViewBag to pass data:
public ActionResult _Alerts(UserADInfoModel model, List<string> groups)
{
DataRowCollection drColl = Core.GetAlerts(model);
ViewBag.Alerts = drColl;
var path = #"Exchange Migration data 10-25-17.csv";
using (TextFieldParser csvParser = new TextFieldParser(path))
{
// ...
while (!csvParser.EndOfData)
{
string[] fields = csvParser.ReadFields();
model.pin = fields[0];
model.tDate = fields[2];
model.stat = fields[6];
}
}
return PartialView(model);
}
_Alerts.cshtml:
#model UserADInfoModel
#if (#Model.pin == Model.SAM)
// ...
// ... #Model.tDate ... #Model.stat ...

How to display audit trail on a ballon

I have created Audit trail and it works fine. you can see all the changes and even the name of the table edited. Now i want to display changes on the popup. Once the user edit some fields, i want to display fieldname,oldvalue,newvalue,username and date.Only once you click on the balloon.
I have no idea on how i can do that. I have implemented the balloon which you can click and view the changes but it doesn't work.
How can i display all the changes on the balloon
Ballon i have created: i have customize it the way i want it if there's an edit
<div class="small-chat-box fadeInRight animated">
<div class="left">
<div class="author-name">
Claim Edit <small class="chat-date">
<br>09-06-2016 12:00 pm
</small>
</div>
<div class="chat-message active">
Username: JJ
<br>fieldname: Surname
<br>oldvalue: small
<br>newvalue big
<br>date: #DateTime.Now
</div>
</div>
</div>
my audit method which works fine
public static List<ClaimAudit> GetClaimLog(SidDbContext db, int claimId)
{
--------------------
foreach (var entry in changeTrack)
{
if (entry.Entity != null)
{
string entityName = string.Empty;
string state = string.Empty;
switch (entry.State)
{
case EntityState.Modified:
entityName = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;
state = entry.State.ToString();
foreach (string prop in entry.OriginalValues.PropertyNames)
{
object currentValue = entry.CurrentValues[prop];
object originalValue = entry.OriginalValues[prop];
if (!currentValue.Equals(originalValue))
{
ClaimLogs.Add(new ClaimAudit
{
tableName = entityName,
state = state,
fieldName = prop,
oldValue = Convert.ToString(originalValue),
newValue = Convert.ToString(currentValue),
userId = "JJ",
UpdateDate = DateTime.Now,
CommentsId = 1,
ClaimId = claimId
});
}
}
break;
}
}
}
calling my update function on save
public async Task<bool> UpdateClaimVehicle(ClaimVehicle vehicleModel)
{
List<ClaimAudit> ClaimLogs = new List<ClaimAudit>();
using (IBaseDataRepository<ClaimVehicle> bs = new BaseRepository<ClaimVehicle>())
{
using (SidDbContext db = new SidDbContext())
{
if (vehicleModel != null)
{
var oldClaim = db.ClaimVehicles.FirstOrDefault(x => x.ClaimId == vehicleModel.ClaimId);
oldClaim.VehicleMakeModelId = vehicleModel.VehicleMakeModelId;
oldClaim.VehicleRegistrationNumber = vehicleModel.VehicleRegistrationNumber;
oldClaim.VehicleYearModel = vehicleModel.VehicleYearModel;
oldClaim.VinNumber = vehicleModel.VinNumber;
ClaimLogs = GetClaimLog(db, oldClaim.ClaimId);
db.claimAuditLog.AddRange(ClaimLogs);
db.SaveChanges();
}
return true;
}
}
}
Here i was trying to display it on the view first,but it says model does not exist
#model Business.Models.ClaimDetailsModel
#foreach (var item in Model) //error here
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ClaimId)
</td>
</tr>
}

How do I retrieve and save the data out of a dynamically created control in a dynamically created RadGrid

Ok here is the scenario. I have created a completely data driven Radgrid with only 2 static buttons on the page, Save and Cancel. The Radgrid is created dynamically, as well as all the data in the grid (from MS SQL). Here is the tricky part, I have a template column that will contain a control. The type of control is determined again by the data in SQL. I.e., data is 6, I need to return a RadTextBox populated with data from SQL, 5 = RadComboBox, also populated... you get the jist. I have a total of 50 records, so I have around 50 controls, all populated with data which can change and be saved. That is the hard part. I have been stuck for 2 days trying to figure out how to get to the RadGrids cell level, find the control, determine what type of control it is, retrieve the lastest data from that control and save it back out to the Database. The code works, I just need help finding the controls and saving the data...
I need to hit the Save button, which in turn gets all the data and saves it to db. I cannot show you all my code because the codebehind is close to 600 lines. but I will demonstrate with one.
I am giving the controls IDs based on a unique value from that row, so ID="c" = x where x is the unique value.
page.aspx
<form id="formUnionActivityProtestor" runat="server">
<asp:HiddenField ID="hiCaseId" runat="server" />
<asp:HiddenField ID="hiCaseSequence" runat="server" />
<telerik:RadScriptManager runat="server" ID="RadScriptManager1" ScriptMode="Release">
</telerik:RadScriptManager>
<div id="headDiv">
<h2>Blah blah blah</h2>
<h3>blah zeyblah</h3>
<telerik:RadButton runat="server" ID="btnSaveUA" CausesValidation="true" OnClick="btnSaveUA_Click"
Text="Save Union Activity" Skin="Web20" Font-Size="12px" Width="145" Font-Bold="true">
</telerik:RadButton>
<telerik:RadButton runat="server" ID="btnCancel" OnClientClicking="ReadOnly"
Text="Cancel Changes" Skin="Web20" Font-Size="12px" Width="145" Font-Bold="true">
</telerik:RadButton>
</div>
<hr />
<div id="gridContainer" runat="server">
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</div>
</form>
page.aspx.cs
protected void Page_Init(object sender, System.EventArgs e)
{
radgrid = new RadGrid();
radgrid.ID = "radgrid";
radgrid.PreRender += new EventHandler(radUAGrid_PreRender);
PlaceHolder1.Controls.Add(radgrid);
this.radgrid.NeedDataSource += new GridNeedDataSourceEventHandler(this.grid_NeedDataSource);
radgrid.ItemDataBound += new Telerik.Web.UI.GridItemEventHandler(this.radgrid_ItemDataBound);
radgrid.MasterTableView.DataKeyNames = new string[] { "q_SortValue" };
radgrid.MasterTableView.AutoGenerateColumns = false;
radgrid.MasterTableView.ShowHeader = false;
radgrid.BorderColor = System.Drawing.Color.Gray;
GridBoundColumn boundColumn;
boundColumn = new GridBoundColumn();
boundColumn.ItemStyle.Width = 600;
boundColumn.ItemStyle.CssClass = "prompt";
boundColumn.DataField = "q_Prompt";
radgrid.MasterTableView.Columns.Add(boundColumn);
GridTemplateColumn templateColumn = new GridTemplateColumn();
templateColumn.ItemTemplate = new TemplateColumn("q_QuestionnaireTypeID");
//templateColumn.ItemStyle.Width = 0;
templateColumn.DataField = "q_QuestionnaireTypeID";
templateColumn.UniqueName = "q_QuestionnaireTypeID";
radgrid.MasterTableView.Columns.Add(templateColumn);
boundColumn = new GridBoundColumn();
boundColumn.Display = false;
boundColumn.ItemStyle.CssClass = "hidecol";
boundColumn.DataField = "t_QuestionnaireTypeDescription";
radgrid.MasterTableView.Columns.Add(boundColumn);
}
public partial class TemplateColumn : System.Web.UI.Page ,ITemplate //adding template fields
{
string fieldName = "";
int controlTypeID = 0;
DataTable dt;
int counter = 1;
UnionActivity refMgr = new UnionActivity(Global.ICEConnectionString);
public TemplateColumn(string fieldName)
{
this.fieldName = fieldName;
}
public int getQuestionTypeID(int count)
{
int k = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == count
select (Int32)dr["q_QuestionnaireTypeID"]).FirstOrDefault();
return k;
}
public void InstantiateIn(Control container)
{
if (counter == 1)
{
dt = UnionActivityDataTable.dt;
}
controlTypeID = getQuestionTypeID(counter);
if (controlTypeID == 5)
{
int QID = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (int)dr["q_QuestionnaireInstanceID"]).FirstOrDefault();
int QQID = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (int)dr["q_QuestionnaireInstanceQuestionID"]).FirstOrDefault();
string answer = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (string)dr["a_Answer"]).FirstOrDefault();
DataTable dt1;
dt1 = getDropDownList(QID, QQID);
RadComboBox cb = new RadComboBox();
foreach (DataRow row in dt1.Rows)
{
RadComboBoxItem item = new RadComboBoxItem();
item.Text = row["DisplayValue"].ToString();
item.Value = row["DDID"].ToString();
if (answer == item.Text)
{
cb.SelectedValue = item.Value;
}
cb.Items.Add(item);
item.DataBind();
}
string x = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select Convert.ToString((int)dr["a_QuestionnaireInstanceQuestionID"])).FirstOrDefault();
cb.ID = "c" + x;
container.Controls.Add(cb);
}
}
DataTable getDropDownList(int QID, int QQID)
{
DataTable dt2 = new DataTable();
try
{
using (refMgr)
{ //retrieving qicr_QuestionnaireInstanceCaseReferenceID
using (DataTable getDropDownData = refMgr.DynamicDropDownData(QID, QQID))
{
if (getDropDownData != null)
{
dt2 = getDropDownData;
}
}
}
}
catch (Exception ex)
{
}
return dt2;
}
}
after page load I look at the source and this is the insert for the combobox...
<td class="rcbInputCell rcbInputCellLeft" style="width:100%;">
<input name="radgrid$ctl00$ctl22$c12" type="text" class="rcbInput radPreventDecorate" id="radgrid_ctl00_ctl22_c12_Input" value="Kiosk" readonly="readonly" />
</td>
I need to attach a method to the save button, but I dont know the first place to start. Telerik is good about getting the page built dynamically, but not saving the data back out. (or even finding the controls...)
I have seen something like this done for survey generation. The only difference is that it wasn't using a Grid. Is there a reason why you need to use a grid rather than just dynamically building the controls on the page?
I can suggest a way so that you can easily obtain the values from dynamic controls.
You can introduce an interface that all your survey controls need to implement.
interface ISurveyControl
{
// expose some common properties
int QuestionID {get; set;}
object Value {get; set;}
// and others as required
}
Then create an extension for every type of control that you need in your survey
public class SurveyTextBox : RadTextBox, ISurveyControl
{
public int QuestionID {get; set;}
public object Value
{
get { return Text; }
set { Text = value.ToString(); }
}
}
public class SurveyComboBox : RadComboBox, ISurveyControl
{
public int QuestionID {get; set;}
public object Value
{
get { return SelectedValue; }
set { SelectedValue = value.ToString(); }
}
}
Make sure you use these extended controls when building the survey and populate the common properties correctly.
Then all you need is a helper function to find all ISurveyControl controls from a container, regardless of whether it's a grid or a page.
List<ISurveyControl > FindSurveyControls(Control container)
{
// you can use linq to find all ISurveyControl within the container
// you may need to make this recursive as well
}
You can then iterate through the controls on save, knowing that they hold enough information such as the QuestionID and so on.

C#: How to using global variable with Javascript

everyone!
I'm learning ASP.NET MVC and have some question.
My problem is Passing Data from View to Controller.
This my Code:
#{
string listID = "";
}
and I try to use this variable:
function SubmitDelete() {
var listId = "";
var x = document.getElementsByName("IsCheck");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
listId += x[i].value + ", ";
};
}
#listID = listId;
return listId;
}
Finalize, I want to pass #listID to Controller:
#using (Html.BeginForm("DeleteChecked", "Category", new { listID }, FormMethod.Post)){ }
It is simple problem about multi delete with checkbox.
Help me, please.
You cannot pass a javascript variable to your controller.
But you can post it as part form data with the help of hidden field.
Better add a hidden field and set it in a Javascript and post
#using (Html.BeginForm("DeleteChecked", "Category", FormMethod.Post)){
Html.HiddenFieldFor(m=>m.MyList, new {#id="my-list-data"})
..other controls and your submit button
}
In a Javascript
function SubmitDelete() {
var listId = "";
var x = document.getElementsByName("IsCheck");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
listId += x[i].value + ", ";
};
}
$('#my-list-data').val(listId);
}
You cannot do that.
The aspx\ascx\cshtml etc. page is built in the server side while the js is computed on the client's side.
You can add C# string to js functions but they will be hard coded when they get to the client.
All the C# expression are evaluated before they get to the client and before the js is computed.
Here's an example:
This is what you see on the aspx\ascx\cshtml file.
<%
string str = 'test';
%>
function jsFunc(){
var myVar = '<%=str%>';
}
This is what the client gets:
function jsFunc(){
var myVar = 'test';
}

Categories

Resources