I want to pass the values from database list to the ViewModels' local variable in controller. I wanted to use GetValue method to do so but it doesn't exist in this context and I have no idea why.
public ActionResult Index()
{
MySQL msql = new MySQL();
List<string> results = msql.SelectList("Select * from table");
var model = new List<MyViewModels>(results.Count);
for (int i = 0; i < results.Count; i++)
{
model.Add(new MyViewModels() {
//this is want I want to do but GetValue method doesn't exist
bID = results[i].GetValue("bID");
status = results[i].GetValue("status")
});
}
return View(model);
}
Because results is a List<string> you are effectively trying to call "".GetValue("bID") which is not possible. Strings have no GetValue function.
This also does not make any sense
List<string> results = msql.SelectList("Select * from table");
This will ONLY work if the table only has one column.
Related
as you can see I have ten team in my database, and here's my code, now I want to generate randomly matches in asp.net C#
in this code the problem is that "d" is a list and the return type of Data is object,
the the picture of error is below.
note in database team_id and team_name in relation when you call team id team_name will be show or call.
function is in service and service is calling in controller.
[HttpGet("DoMatch")]
public IActionResult DoMatch()
{
var res= _matchService.DoMatch();
return Ok(res);
}
public ResponseModel DoMatch()
{
var random = new Random();
List<Team> list = _context.Team.ToList();
Dictionary<int, List<Team>> d = new Dictionary<int, List<Team>> { };
var count = list.Count();
for (int i = 0; i < count / 2; i++)
{
List<Team> temp = new List<Team>();
int index1 = random.Next(list.Count);
temp.Add(list[index1]);
list.RemoveAt(index1);
int index2 = random.Next(list.Count);
temp.Add(list[index2]);
list.RemoveAt(index2);
d.Add(i, temp);
}
return new ResponseModel
{
Data = d,
IsSuccess = true
};
}
the error or exception is:
System.NotSupportedException: The collection type 'System.Collections.Generic.Dictionary2[System.Int32,System.Collections.Generic.List1[Fantasy_League.Models.Team]]' on 'FantasyLeague.Models.ViewModels.ResponseModel.Data' is not supported.
The actual problem that you're running into, as described by the exception message you're getting, is that Dictionary<int, ...> cannot be serialized to be sent back in the web response. JSON requires each key to be a string. So you'll need to decide what you actually want your model to look like. Most likely it would work just fine to use the Values from your dictionary.
Data = d.Values,
That will make the JSON data come across as an array where each element is an array with the paired teams in it.
But Fildor makes a good point in his comment, that you could do this more easily by shuffling and pairing up adjacent teams:
Data = list.OrderBy(t => random.Next()).Chunk(2);
Then all that fancy dictionary logic goes away.
Hey all I am new to Razor MVC and wanted to make a select box that has the past 10 years listed inside it (2016, 2015, 2014, etc....).
This is my current Controllers code:
public ActionResult loadPast10Years()
{
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag["last10Years"] = last10Years;
return View();
}
And my Razor code:
#Html.DropDownList("last10Years", (SelectList)ViewBag["last10Years"], "--Select One--")
But I have an error when loading the page that says:
InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'last10Years'.
So... What am I missing?
This is how I would do it in the view
#Html.DropDownList("Last Ten Years", (IEnumerable<SelectListItem>)ViewBag.LastTenYears, "Select A Year")
and in your Action
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag.LastTenYears = new SelectList(last10Years);
You can see a demo here
Following from your comment please find below my updated answer.
I would first create a Model class which we will be using in our view. In this model class you can have your appropriate properties. For now we're only going to be using SelectlistItem
so our class will look like
public class ViewModel
{
public IEnumerable<SelectListItem> LastTenYears { get; set; }
}
Then in our controller we can create a method which will provide us the information for our drop down.
public IEnumerable<SelectListItem> GetLastTenYears()
{
List<SelectListItem> ddl = new List<SelectListItem>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
ddl.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
}
IEnumerable<SelectListItem> lastTenYears = ddl;
return lastTenYears;
}
Now we want to pass this data to the view. For argument sake I will use Index as a view but you can pass it to whatever view you like. So we will change our Index action to
public ActionResult Index()
{
ViewModel viewModel = new ViewModel();
viewModel.LastTenYears = GetLastTenYears(); //get the drop down list
return View(viewModel); //we're passing our Model to the view
}
Finally, we want to make sure our view knows which Model to use so we will do the following the beging of the Index.cshtml file
#model YourNameSpace.ViewModel
and our DropDownList helper method will now change to point to the property in our Model class as
#Html.DropDownList("Last Ten Years", Model.LastTenYears, "Please select a year")
There are few issue in your code right now.
Don't name the ViewBag key same as the DropDownList name, they don't
work well together, you can change the ViewBag Key name to something like last10YearsOptionsinstead oflast10Years`, so that it is different than control name.
You have not create SelectList in controller before adding to ViewBag, but you are casting it to SelectList in View.
In ViewBag values are stored like ViewBag.SomeKey= "SomeValue", but you are doing it wrong way.
After Fixing the above problems your code will look like :
ViewBag.last10YearsOptions = last10Years.Select(x => new SelectListItem()
{
Text = x.ToString(),
Value = x.ToString()
}
);
and then in View:
#Html.DropDownList("last10Years",
"--Select One--",
ViewBag.last10YearsOptions as IEnumerable<SelectListItem>,
null )
ViewBag is not a dictionary with key value pairs.
also DropDownList works with ICollection ithink
so this code works form
#Html.DropDownList("last10Years", new SelectList(ViewBag.last10YearsOptions), "Select one from here")
Controller is here;
public ActionResult loadPast10Years()
{
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag.last10Years = new SelectList(last10Years);
return View();
}
And View
#Html.DropDownList("last10Years", "--Select One--")
I am trying to access a stored procedure that retrieves a page using an id.
But I am getting an error:
Error 1 Cannot implicitly convert type
'System.Data.Entity.Core.Objects.ObjectResult<StorePageCMS.Models.mn_StorePage_Select_One_Result>' to 'StorePageCMS.Models.StorePage'
I am not sure how to fix this. The stored precedure that comes from dbEntities from SQL Server, does take an int parameter.
Any help is much appreciated.
public StorePage Get(int StorePageID)
{
using (dbEntities db = new dbEntities())
{
StorePage storepage = db.mn_StorePage_Select_One(StorePageID);
if (storepage == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return storepage;
}
}
UPDATE
I rewrote the method this way:
public List<StorePage> Get(int StorePageID)
{
List<StorePage> storepagelist = new List<StorePage>();
using (dbEntities db = new dbEntities())
{
var results = db.mn_StorePage_Select_One(StorePageID).ToList();
foreach (var result in results)
{
var storepage = new StorePage()
{
StorePageID = result.StorePageID,
SPPreambleID = result.SPPreambleID,
Title = result.Title,
SEOTitle = result.SEOTitle,
ParentStorePageID = result.ParentStorePageID ?? -1,
Meta = result.Meta,
Image = result.Image,
ImageLink = result.ImageLink,
Blurb = result.Blurb,
RegionID = result.RegionID,
Footer = result.Footer
};
storepagelist.Add(storepage);
}
return storepagelist;
}
}
Does this looks more correct?
2 UPDATE
Does this looks correct?
If you're not using the Code First model of Entity Framework
Since StorePageCMS.Models.mn_StorePage_Select_One_Result has no conversion to StorePage, I'm assuming it's a stored procedure result. If that's a stored procedure result (of mn_StorePage_Select_One), you need to map it's result to the StorePage model instead in the EDMX designer.
Here, you'd need to say it returns a collection of StorePageCMS.Models.StorePage Entities.
I'm passing a list of guids in a GET request from a JQuery Ajax call.
on my ASP.NET controller side I want to iterate through the list and update the Display_Sort column to match my newly sorted list.
My ID is a Guid and I'm getting a type error in the following code, because it's a string that I'm passing to the Db. However, I can't seem to convert the item(string) into a Guid.
I've tried Guid(item) and it would allow the constructor. Not sure what I'm missing.
Here is the code:
//REORDER HOME ASSETS
public ActionResult ReOrderHome()
{
using (var db = new IFEntities())
{
var myString = Request.QueryString;
var i = 1;
foreach (var item in myString)
{
var myObj = db.HomeContents.Find(item);
myObj.display_order = i;
db.SaveChanges();
i++;
}
}
You can convert item to GUID and then compare like this.
var myObj = db.HomeContents.Find(new Guid(item));
Or, you can use select instead of find. Syntax for select --
foreach (var item in myString)
{
var myObj = db.HomeContents.Select(p => p.<GUID_COLUMN_NAME> == item);
myObj.display_order = i;
db.SaveChanges();
i++;
}
Replace GUID_COLUMN_NAME with actual column name.
Im gettin this error but i dont know what it is. I've looked for the answer but none can answer main or maybe im just missing something. Here my code:
Connection db = new Connection();
public ActionResult Index()
{
ViewBag.query = from input in db.field
where input.ID_FIELD == 1
select new {
type = input.FIELD_TYPE
};
return View();
}
and the view side
#foreach (var item in ViewBag.query)
{
#item.type//error here: 'object' does not contain a definition for 'type', why???
}
And if i make a simple select with where clause, work ok
public ActionResult Index()
{
ViewBag.query = from input in db.field
where input.ID_FIELD == 1
select input.FIELD_TYPE;
return View();
}
What could be my problem? I've seem many toturials doing the same and works great like this one i did just now:
int[] number = { 1, 2, 3, 4, 5 };
var query = from num in number
let x = num + num + num
select new {avg = x};
foreach (var item in query)
{
Console.WriteLine(item.avg);
}
Everything is ok here. Why could be the problem??
You can't return an anonymous type from a method. Instead, create a new type and return that type.
For example:
ViewBag.query = from input in db.field
where input.ID_FIELD == 1
select new MyType() {
someField = input.FIELD_TYPE
};
public class MyType
{
public int someField {get;set;}//compatible with whatever type FIELD_TYPE is.
}
In your Last Example you are Not using 'item.type'. Apart from that, System.Object does Not contain a property 'type'. You can use 'GetType()', though.
See here for reference.
The problem is that ViewBag is dynamic, but the anonymous object you're storing in it is not, so the compiler cannot access its properties directly. You could just store a collection of values in the ViewBag property rather then the whole query:
Connection db = new Connection();
public ActionResult Index()
{
ViewBag.types = from input in db.field
where input.ID_FIELD == 1
select input.FIELD_TYPE;
return View();
}
and then
#foreach (var type in ViewBag.types)
{
#type
}