i have a model and i send substring one field on this model and return to a view for show in gridview
my model is:
public class News
{
public int ID { get; set; }
[MaxLength(300)]
public string Title { get; set; }
[DataType(DataType.MultilineText)]
[MaxLength]
public string Content { get; set; }
[ReadOnly(true)]
public DateTime Date { get; set; }
[Column("PictureID")]
public virtual Picture Picture { get; set; }
//public IList<Picture> PicID { get; set; }
[Column("NewsTypeID",Order=1)]
public virtual NewsType NewsType { get; set; }
public ICollection<Tag> Tags { get; set; }
public News()
{
Tags = new List<Tag>();
}
}
when i send this model by myController:
public ActionResult ShowNews()
{
var data = new DatabaseContext();
var news = data.newsInfo.ToList();
return View(news);
}
it is ok and show properly in gridview
but if send this model by this cod in controller:
public ActionResult ShowNews()
{
var data = new DatabaseContext();
var news = data.newsInfo.Select(x => new { Content = x.Content.Substring(0,200), x }).ToList();
return View(news);
}
show this Error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType02[System.String,NewsAgency.Models.News]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[NewsAgency.Models.News]'.
i have send substring one of the field
what is problem?
You have created list of anonymous objects in this statement:
data.newsInfo.Select(x => new { Content = x.Content.Substring(0,200), x }).ToList();
And you have send it as model to your view:
View(news);
But, in your view you have set model type as List<News>. So, the exception is throwned. Try to change your code as:
var news = data.newsInfo.AsEnumerable().Select(x => { x.Content = x.Content.Substring(0,200); return x; }).ToList();
If you want to send whole Content values along with substrings, then I recommend to use first way and get the substring of all item's Content with razor inside view.
Related
I want to return a list of links to a web page when it loads. Right now I have a model called SsoLink.cs bound to the page. I would like to return a list, so I have created another model called SsoLinks.cs that has a List. In my helper function, I keep getting "object not set to an instance of an object".
SsoLink.cs
public class SsoLink
{
public enum TypesOfLinks
{
[Display(Name="Please Select a Type")]
Types,
Collaboration,
[Display(Name="Backups & Storage")]
Backups_Storage,
Development,
[Display(Name="Cloud Services")]
Cloud_Services,
[Display(Name="Human Resources")]
Human_Resources,
Analytics
}
public string Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Owner { get; set; }
public string OwnerEmail { get; set; }
public string LinkDescription { get; set; }
public TypesOfLinks LinkType { get; set; }
}
SsoLinks.cs
public class SsoLinks
{
public List<SsoLink> Links {get; set;}
}
GetLinksHelper.cs
public partial class SsoLinkHelper
{
public static SsoLinks GetLinks()
{
var ssoList = new SsoLinks();
try
{
//search the index for all sso entries
var searchResponse = _client.Search<SsoLink>(s => s
.Index(_ssoLinkIndex)
.Size(500)
.Query(q => q
.MatchAll()
)
);
if (searchResponse.Documents.Count == 0)
{
return ssoList;
}
ssoList.Links.AddRange(searchResponse.Hits.Select(hit => new SsoLink() {Id = hit.Source.Id, Name = hit.Source.Name, Url = hit.Source.Url, Owner = hit.Source.Owner}));
return ssoList;
}
catch (Exception e)
{
Log.Error(e, "Web.Helpers.SsoLinkHelper.GetLinks");
return ssoList;
}
}
}
While debugging, It is failing at SsoLinks.Links.AddRange(etc). How can I add a new SsoLink to the ssoList for every item found in my query?
Edit: Here is a screenshot of the error while debugging.
The null reference exception looks like it comes from ssoList.Links being null when calling AddRange on it, so it needs to be initialized to a new instance of List<SsoLink> before calling AddRange().
Russ's answer led me down the right path, I ended up just needing to change my view to:
#model List<SharedModels.Models.SsoLink>
rather than
#model SharedModels.Models.SsoLink
and do away with the SsoLinks model.
I am student developper in ASP .NET MVC Platform. Maybe my question can be simple but although I try to convert or cast my textDate column , I did not show it in column of table at view succesfully. I am facing with empty value in my view. My question is if we have a smalldatetime column in our SQL database how can we show it our table in view with converting or casting ?
My method :
public JsonResult Get()
{
// Example List
var listMsg = reader.Cast<IDataRecord>().Select(x => new
{
textId = (int)x["textId"],
textOwner = (string)x["textOwner"],
textDate =(x["textDate"].ToString()) // Empty Line it does not work
}).ToList();
return Json(new { listMsg = listMsg }, JsonRequestBehavior.AllowGet);
}
My model :
public partial class TextMessage
{
public int textId { get; set; }
public string textOwner { get; set; }
public Nullable<System.DateTime> textDate { get; set; }
}
In your model you make textDate object as Nullable<System.DateTime>. So in your public JsonResult Get() method you have to convert x["textDate"]object to datetime object.
You can achieve this by doing:
textDate = DateTime.Parse(x["textDate"])
I faced the same problem in a different situation. I solved it by creating an extra field of type string. Make changes as below
My Model:
public partial class TextMessage
{
public int textId { get; set; }
public string textOwner { get; set; }
public Nullable<System.DateTime> textDate { get; set; }
public string textDateString { get; set; }
}
My Method:
public JsonResult Get()
{
// Example List
var listMsg = reader.Cast<IDataRecord>().Select(x => new
{
textId = (int)x["textId"],
textOwner = (string)x["textOwner"],
textDateString =(x["textDate"].ToString())
}).ToList();
return Json(new { listMsg = listMsg }, JsonRequestBehavior.AllowGet);
}
I have a model DropDownConfiguration which is fetching values from database and populating the dropdown list.
Model:
public class DropDownConfiguration
{
public int ID { get; set; }
public int Quarter { get; set; }
public int Year { get; set; }
public string Project { get; set; }
public string LineID { get; set; }
}
html:
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "ID", "Project"), "-- Select Project --", new { required = true, #class = "form-control" })
I have another model DetailsConfiguration which has all the fields which need be saved into the database.
public class DetailsConfiguration
{
public int Quarter { get; set; }
public int Year { get; set; }
public string Project { get; set; }
public string ItemModel { get; set; }
}
Controller HttpPost:
[ActionName("DetailsForm")]
[HttpPost]
public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
{
DetailsConfiguration detailsConfig = new DetailsConfiguration();
detailsConfig.Quarter = Convert.ToInt32(form["Quarter"]);
detailsConfig.Year = Convert.ToInt32(form["Year"]);
detailsConfig.Project = model.detailsConfig.Project;
detailsConfig.ItemModel = model.detailsConfig.ItemModel;
detailsConfig.LineID = model.detailsConfig.LineID;
floorService.SaveDetails(detailsConfig);
ModelState.Clear();
ViewBag.message = "Success";
return View("DetailsForm");
}
Is there anyway to do something like:
model.detailsConfig.Project = model.dropConfig.Project
I need the selection of Project to be posted back to database through DetailsConfiguration.
You could create a mapper which sets the values of the properties in DropDownConfiguration to DetailsConfiguration.
When you change the dropdown you send the selected DropDownConfiguration to the server. You know exactly what properties you can expect here so you can do something like this:
[HttpPost]
public IHttpActionResult AddDetailsConfiguration(DropDownConfiguration parameter)
{
//check here if values in parameter are set
var detailsConfiguration = new DetailsConfiguration {
Quarter = parameter.Quarter,
Year = parameter.Year,
Project = parameter.Project
}
//Insert detailsConfiguration to database
Return Ok();
}
Note that you have to make sure you send a DropDownConfiguration object on selecting a dropdown item. You could also only send the values you need like this:
[HttpPost]
public IHttpActionResult AddDetailsConfiguration(int quarter, int year, string project)
{
//Check here if values in parameter are set and if values are correct
var detailsConfiguration = new DetailsConfiguration
{
Quarter = quarter,
Year = year,
Project = project
}
//Insert detailsConfiguration to database
Return Ok();
}
I need to populate a dropdown with some data i get from a SOAP server. The server provides me an array of the companies.
How would i use it to populate the DD ?
Here is my User class:
public class Usuario
{
public string Nome { get; set; }
public string Token { get; set; }
public IEnumerable<SelectListItem> Unidades { get; set; }
}
Here is where i receive the companies and send it to the view, i get it from another Action that is redirecting to this Action:
var usuario = TempData["objUsuario"] as UsuarioSSO;
if (usuario == null) return RedirectToAction("Index", "Login");
if (usuario.UsuarioUnidades == null)
{
ModelState.AddModelError("", "Usuário não possui unidades");
return View();
}
var model = new Models.Usuario
{
Unidades = usuario.UsuarioUnidades.ToList().Select(x => new SelectListItem
{
Value = x.CodigoEmitente.ToString(),
Text = x.NomeFantasia
})
};
return View(model);
Here is how i'm trying to display it:
#Html.DropDownListFor(x => x.Unidades, new SelectList(Model.Unidades))
I have already tried of everything but it won't work, i get some conversion errors and when i can make it work it won't display the content, it will only display the object inside the Text area
System.Web.Mvc.SelectListItem
You need to have one property for the selected item and the list of available items, e.g.:
public class Usuario
{
public string Nome { get; set; }
public string Token { get; set; }
public string Unidade { get; set; }
public IEnumerable<SelectListItem> Unidades { get; set; }
}
and then create the drop-down like:
#Html.DropDownListFor(x => x.Unidade, Model.Unidades)
You can directly supply the Unidades as it is already IEnumerable<SelectListItem>.
P.S.: I guessed the singular of Unidades as I do not speak your langauge, whatever it is. I recommend to ALWAYS use english in source code.
Your model needs a value type property to bind the selected option to. If CodigoEmitenteis typeof int then you model property needs to be
public int SelectedUnidades { get; set; }
and you need to assign the SelectList to another property in your view model or to a ViewBag property
ViewBag.UnidadesList = new SelectList(usuario.UsuarioUnidades, "CodigoEmitente", "NomeFantasia");
Then in the view
#Html.DropDownListFor(x => x.SelectedUnidades, (SelectList)ViewBag.UnidadesList)
I have DropDownList that read fils from my database and show this files in my DropDownList.
The current solution is show on my DropDownListItem System.Web.Mvc.SelectList instead of my Object property. I want to include a drop down list of my object (read from database) across my webpage.
This is my object:
public class MyObject
{
public int id { get; set; }
public string fileName { get; set; }
public string browser { get; set; }
public string protocol { get; set; }
public string family { get; set; }
}
My controller:
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
ViewBag.Files = lList;
return View();
}
Index.cshtml
#Html.DropDownList("File",new SelectList(ViewBag.Files))
What i want to see in my DropDownList is my protocol property.
Try like this:
#Html.DropDownList("File", new SelectList(ViewBag.Files, "id", "fileName"))
Try this
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").DistinctBy(x=> x.protocol).ToList();
ViewBag.Files = new SelectList(list,"Id","protocol");
return View();
}