Persist the selected value of static dropdownlist in MVC4 - asp.net-mvc-4

#Html.DropDownList("CType",new List<SelectListItem> {
new SelectListItem{Text = "All",Value = "0"},
new SelectListItem{Text = "Outgoing",Value ="Outgoing"},
new SelectListItem{Text = "Incoming", Value ="Incoming"},
}, new { #class = "form-control input-md"})
If I'm selecting the second value, I want to persist that selected value of dropdown across multiple requests

Related

Unable to add column between two columns using Google spreadsheet Api

I have a Google spreadsheet. On my E column, I want to add recent month with the year (eg: Sept 2017) if not available on E column.Suppose there is (Aug 2017) and now when I add (Sept 2017) it adds but it replaces the existing column that is Aug 2107. My requirement is to keep both: newly added (Sept 2017) and (Aug 2017).
I want recent month on E column and shift existing column on the right that is F column. I'm doing this using C#.
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = GetCredential(),
ApplicationName = ApplicationName,
});
String spreadsheetId = "1lZnvQe6lTGG81hyuQvf7HjH8YpnIadFlNHjFUq_G-5Q";
String range = "E1";
SpreadsheetsResource.ValuesResource.GetRequest getRequest = service.Spreadsheets.Values.Get(spreadsheetId, range);
Data.ValueRange response = getRequest.Execute();
string recentMonth = DateTime.Now.ToString("MMM yyyy");
var recentMonthArrayValue = new List<string[]>();
recentMonthArrayValue.Add(new string[] { recentMonth });
if (response.Values[0][0].ToString() != recentMonth)
{
DateTime now = DateTime.Now;
var currentMonthStartDate = new DateTime(now.Year, now.Month, 1).ToShortDateString();
Data.BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new Data.BatchUpdateSpreadsheetRequest();
batchUpdateSpreadsheetRequest.Requests = new List<Data.Request>();
Data.Request request = new Data.Request();
batchUpdateSpreadsheetRequest.Requests.Add(request);
request.UpdateCells = new Data.UpdateCellsRequest();
var gridCoordinate = new Data.GridCoordinate();
gridCoordinate.ColumnIndex = 5;
gridCoordinate.SheetId = 0;
request.UpdateCells.Start = gridCoordinate;
request.UpdateCells.Fields = "*";
request.UpdateCells.Rows = new List<Data.RowData>();
var rowData = new Data.RowData();
request.UpdateCells.Rows.Add(rowData);
rowData.Values = new List<Data.CellData>();
var cellData = new Data.CellData();
cellData.UserEnteredValue = new Data.ExtendedValue();
cellData.UserEnteredValue.FormulaValue = "=TEXT(\"" + currentMonthStartDate + "\",\"MMM yyyy\")";
rowData.Values.Add(cellData);
SpreadsheetsResource.BatchUpdateRequest batchUpdateRequest = service.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, spreadsheetId);
batchUpdateRequest.Execute();
}
}
catch (Exception e)
{
//throw;
}
}
public static UserCredential GetCredential()
{
UserCredential credential;
using (var stream =new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
return credential;
}
}
Check the insert an empty row or column guide in Sheets API:
The following spreadsheets.batchUpdate request inserts two blank
columns at column C. A second request inserts three empty rows at row
1. The inheritBefore field, if true, tells the API to give the new columns or rows the same properties as the prior row or column;
otherwise the new columns or rows acquire the properties of those that
follow them. inheritBefore cannot be true if inserting a row at row 1
or a column at column A.
The request protocol is shown below. The Updating Spreadsheets guide
shows how to implement a batch update in different languages using the
Google API client libraries.
POST https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate
{
"requests": [
{
"insertDimension": {
"range": {
"sheetId": sheetId,
"dimension": "COLUMNS",
"startIndex": 2,
"endIndex": 4
},
"inheritBefore": true
}
},
{
"insertDimension": {
"range": {
"sheetId": sheetId,
"dimension": "ROWS",
"startIndex": 0,
"endIndex": 3
},
"inheritBefore": false
}
},
],
}

sample of kendo combo for relation table with id and value

i'm using kendo ui in my asp.net mvc 4 with razor views and encounter problem with kendo combo when the list load from an action via ajax with sending parameters to the server like the sample here:HERE
becuase the table has more then 2,000 rows.
when i load the edit page, the combo load and filter the data as expected, but the value of this field is - [object object].
i did declare the .DataTextField("ProffName") + .DataValueField("ID")
My ClientsController:
public ActionResult Edit(int id = 0)
{
Clients clients = db.Clients.Find(id);
if (clients == null)
{
return HttpNotFound();
}
ViewData["MyAgency"] = new SelectList(db.Agency, "ID", "AgentName", clients.AgencyId);
ViewData["MyCategory1"] = new SelectList(db.CategoryTbl, "ID", "category", clients.CategoryId);
List<SelectListItem> obj = new List<SelectListItem>();
obj.Add(new SelectListItem { Text = "male", Value = "1" });
obj.Add(new SelectListItem { Text = "female", Value = "2" });
obj.Add(new SelectListItem { Text = "choose", Value = "0" });
ViewData["MyMin"] = obj;
ViewBag.ProffID = new SelectList(db.ProfTBL, "ID", "ProffName", clients.ProffID);
ViewBag.Metapel = new SelectList(db.Workers, "ID", "WorkerName", clients.Metapel);
return View(clients);
}
My ProffController:
public ActionResult ProffVM_Read(string text)
{
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName });
if (!string.IsNullOrEmpty(text))
{
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text));
}
return Json(Proff_Tbl, JsonRequestBehavior.AllowGet);
}
and the Kendo combo:
#Html.Label("Proff")
#(Html.Kendo().ComboBoxFor(model => model.ProffID)
.Name("proffCbo")
.DataTextField("ProffName")
.DataValueField("ID")
.Events(e => e
.Select("proffCbo_select")
.Change("proffCbo_change")
)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("ProffVM_Read", "Proff")
.Data("onAdditionalData");
});
})
)
where am i wrong ???
i can change this combo to textbox but... i have to realize the magic.
Thanks
Change these two lines
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName });
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text));
to
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName }).ToList();
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text)).ToList();

DropDownlist value is inserted as System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]

I'm trying to insert value of dropdownlist in db but instead of storing its selected value it is
storing this value System.Collections.Generic.List1[System.Web.Mvc.SelectListItem].
Here is my code.
View:
#Html.DropDownListFor(m =>m.propertyType, (List<SelectListItem>) ViewData["property"])
Model:
public string propertyType { get; set; }
[HttpGet]
public ActionResult EditProfile()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Private Residence", Value = "Private Residence" });
items.Add(new SelectListItem { Text = "Office", Value = "Office" });
items.Add(new SelectListItem { Text = "Place of worship", Value = "Place of worship" });
items.Add(new SelectListItem { Text = "Commercial Parking lot", Value = "Commercial Parking lot" });
items.Add(new SelectListItem { Text = "Retail", Value = "Retail" });
items.Add(new SelectListItem { Text = "Academic Institution", Value = "Academic Institution" });
items.Add(new SelectListItem { Text = "Other", Value = "Other" });
ViewData["property"] = items;
return View();
}
[HttpPost]
public ActionResult EditProfile(EditProfile edit)
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Private Residence", Value = "Private Residence" });
items.Add(new SelectListItem { Text = "Office", Value = "Office" });
items.Add(new SelectListItem { Text = "Place of worship", Value = "Place of worship" });
items.Add(new SelectListItem { Text = "Commercial Parking lot", Value = "Commercial Parking lot" });
items.Add(new SelectListItem { Text = "Retail", Value = "Retail" });
items.Add(new SelectListItem { Text = "Academic Institution", Value = "Academic Institution" });
items.Add(new SelectListItem { Text = "Other", Value = "Other" });
ViewData["property"] = items;
string UserName = User.Identity.Name;
var query = from q in Session.Query<Registration>()
where q.Email == UserName
select q;
if (query.Count() > 0)
{
foreach (var update in query)
{
update.contactNo = edit.contactNo;
update.occupation = ViewData["property"].ToString();
}
}
else ModelState.AddModelError("","");
Session.SaveChanges();
return View();
}
Any help will be highly appreciated.Thanks!
I always try to avoid using ViewData or ViewBag. Try following for this porpose:
Create static class for all dropdowns:
public static class MyDrops
{
public static List<SelectListItem> GetList()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Private Residence", Value = "Private Residence" });
items.Add(new SelectListItem { Text = "Office", Value = "Office" });
items.Add(new SelectListItem { Text = "Place of worship", Value = "Place of worship" });
items.Add(new SelectListItem { Text = "Commercial Parking lot", Value = "Commercial Parking lot" });
items.Add(new SelectListItem { Text = "Retail", Value = "Retail" });
items.Add(new SelectListItem { Text = "Academic Institution", Value = "Academic Institution" });
items.Add(new SelectListItem { Text = "Other", Value = "Other" });
return items;
}
}
Then in your View:
#Html.DropDownListFor(m =>m.propertyType, MyDrops.GetList())
this line is crazy:
update.occupation = ViewData["property"].ToString();
it should be:
update.occupation = edit.propertyType;

Adding id to mvc4 dropdownlist

This is my code:
#Html.DropDownListFor(m=> m.IsCurrentlySmoking, new{ onchange="RiskChange(this)", id="IsCurrentlySmokingLeftDrp", SelectList(new List<Object>{
new { value = 0, text = "Fortsatt rökning"},
new {value = 1, text = "Minskat rökning"},
new {value = 2, text = "Röker ej"},
}, "value", "text", 0)}
The code worked fine untill i added the id to it. Now i get the error: CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
What is wrong with the code? I have added id to other mvc form elements that way and it worked perfectly fine.
You messed-up the SelectList and htmlAttributes order. Just change it like this, it will work:
#Html.DropDownListFor(m => m.IsCurrentlySmoking, new SelectList(new List<Object>{
new { value = 0, text = "Fortsatt rökning"},
new {value = 1, text = "Minskat rökning"},
new {value = 2, text = "Röker ej"},
}, "value", "text", 0), new { onchange = "RiskChange(this)", id = "IsCurrentlySmokingLeftDrp" })

jqGrid ASP.NET MVC4 initial sort

I'm using jqGrid as TreeGrid with ASP.NET MVC4 and have one problem:
My Model:
OrdersGrid = new JQGrid
{
Columns = new List<JQGridColumn>()
{
new JQGridColumn
{
DataField = "MeasureId",
// always set PrimaryKey for Add,Edit,Delete operations
// if not set, the first column will be assumed as primary key
PrimaryKey = true,
Visible = false,
Sortable = false
},
new JQGridColumn
{
DataField = "Name",
Width = 100,
Sortable = true
},
new JQGridColumn
{
DataField = "Symbol",
Width = 100
},
},
Width = Unit.Pixel(640),
Height = Unit.Percentage(100),
TreeGridSettings = new TreeGridSettings
{
Enabled = true
},
SortSettings = new SortSettings
{
AutoSortByPrimaryKey = false,
InitialSortColumn = "Name",
InitialSortDirection = SortDirection.Asc
}
};
My Controller:
public JsonResult DataRequested()
{
// Get both the grid Model and the data Model
// The data model in our case is an autogenerated linq2sql database based on Northwind.
var gridModel = new NavigatorModel();
...
var hierarchyRows = from measure in measures
select new
{
MeasureId = measure.MeasureId,
Name = measure.Name,
Symbol = measure.Symbol,
//ParentID = measure.ParentMeasureId != null ? measure.ParentMeasureId.ToString() : "",
tree_loaded = true,
tree_parent = measure.ParentMeasureId,
tree_level =LoadAllRowsExpanded_GetRowLevel(measure.ParentMeasureId, measures),
tree_leaf = LoadAllRowsExpanded_IsLeafRow(measure.MeasureId, measures),
tree_expanded = true
};
//var dataModel = new
// return the result of the DataBind method, passing the datasource as a parameter
// jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
return gridModel.OrdersGrid.DataBind(hierarchyRows.AsQueryable());
}
As above you can see that I'm setting the AutoSortByPrimaryKey set to false, but when the page is loaded, grid looks like that:
When I click on one of columns (Name or Symbol) to sort everything becomes fine - the Measure which is wrongly displayed goes under it's parent.
I have tried also with event to sort after "gridInitialize" but also no success.
Any ideas?