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();
}
Related
I want to get a name from selected id in my view page
First Model
public class Transaction
{
[Key]
public int Id { get; set; }
[Required]
public int supplier_id { get; set; }
[Required]
public string supplier_name { get; set; }
}
Second Model
public class Supplier
{
[Key]
public int supplier_id { get; set; }
[Required]
public string supplier_name { get; set; }
}
View Model
public class EvaluateSheet
{
public IEnumerable<Supplier> Suppliers{ get; set; }
public IEnumerable<Transaction> Transactions { get; set; }
public Transaction Transaction { get; set; }
}
Controller
public IActionResult Sheet11()
{
var sup = _db.Supplier.ToList();
ViewBag.Sup = new SelectList(sup, "supplier_id", "supplier_name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Sheet11(EvaluateSheet objc)
{
Transaction Model = objc.Transaction;
Transaction transaction = new Transaction();
transaction.Id = Model.Id;
transaction.supplier_id = Model.supplier_id;
transaction.supplier_name = Model.supplier_name;
_db.Transaction.Add(Model);
Model.supplier_name = Model.Supplier.supplier_name.Where(Model.Supplier.supplier_id == Model.supplier_id);
_db.SaveChanges();
return RedirectToAction("Index");
}
View Page
#model EvaluateSheet
<form method="post">
<select asp-for="#Model.Transaction.supplier_id" asp-items="#ViewBag.Sup" value="#ViewBag.Sup" class="form-control">
<option selected disabled>--choose supplier--</option>
</select>
<button type="submit" class="btn btn-primary">Add Transaction</button>
I want to automatically insert supplier_name field after I selected supplier_id in my View page into the database.
I have tried this in my controller but it doesn't work
Model.supplier_name = Model.Supplier.supplier_name.Where(Model.Supplier.supplier_id == Model.supplier_id);
Try this:
Define an integer type variable in EvaluateSheet model for example("public int Sup_id { get; set; }") and tag it with DropDownListFor.
In Controller select specific data from supplier table with the help of new define int Sup_id and copy this data in Model(Transaction).
For example:
Transaction Model = new Transaction();
Supplier supl = null;
supl = _db.Supplier.Where(x => x.supplier_id == objc.Sup_id).FirstOrDefault();
Model.supplier_id = supl.supplier_id;
Model.supplier_name = supl.supplier_name;
_db.Transaction.Add(Model);
_db.SaveChanges();
return RedirectToAction("Index");
I am trying to create my first ASP.NET MVC application but since two days I cannot solve my problem.
I am using Entity Framework Code First approach. I want to create DropDownListFor but there is always this error:
System.NullReferenceException
System.Web.Mvc.WebViewPage.Model.get returned null.
My Model:
public class Animals
{
public int AnimalsId { get; set; }
public int ClientsId { get; set; }
public string Name { get; set; }
public int TypesId { get; set; }
public float Age { get; set; }
public float Weight { get; set; }
public virtual Types Types { get; set; }
public IEnumerable<Clients> ClientsList { get; set; }
public virtual ICollection<BookVisit> AnimalsVisits { get; set; }
}
My controller:
public ActionResult Create([Bind(Include = "AnimalsId, ClientsId, Name, TypesId, Age, Weight")] Animals animals)
{
var person = new List<Clients>
{
new Clients { ClientsId = 50, Name = "Timo", Surname = "Werner", Email = "timo.werner#gmail.com", Phone = 123123123 }
};
var animalsView = new Animals
{
ClientsList = person.Select(x => new Clients
{
ClientsId = x.ClientsId
})
};
if (ModelState.IsValid)
{
db.Animals.Add(animals);
db.SaveChanges();
return RedirectToAction("List", "Animal");
}
return View(animalsView);
}
My view (only #model and dropdown):
#model xyz.Models.Animals
#Html.DropDownListFor(model => model.ClientsId, new SelectList(Model.ClientsList, "ClientsId", "Name", "Surname", "Email", "Phone"))
Could you please take a look ?
From the comments, it looks like you are not passing a valid view model object to the view. Your view code is expecting a valid model passed to it and the helper methods are using different properties of that.
public ActionResult Create()
{
var clients = new List<Clients>
{
new Clients { ClientsId = 50, Name = "Timo" },
new Clients { ClientsId = 51, Name = "Microsoft" }
};
var vm = new Animals
{
ClientsList = clients
};
return View(vm);
}
Also your current code which calls the DropDownListFor is wrong. When you create a SelectList from a collection, you have to pass the dataValue field and dataText fields.
#model Animals
#Html.DropDownListFor(model => model.ClientsId,
new SelectList(Model.ClientsList, "ClientsId", "Name"))
This error may also be caused by trying to use a null model in razor view. In such case check if the model is null or not before using it as shown below:
#if (Model != null) {
<a onclick="get('#Url.Action("GetEmployee", "DemoController")', #Model.Id)" ></a>
}
Consider the following model:
public class TagType
{
public int Id { get; set; }
public string Description { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Description { get; set; }
public TagType TagType { get; set; }
public DropDownListViewModel TagTypeViewModel { get; set; }
public int TagTypeId { get; set; }
}
I have the following Action in a controller:
public ActionResult Edit(int id)
{
// Load from database
IEnumerable<TagType> tagTypes = TagTypeDal.GetAll().ToList();
Tag tag = TagDal.Get(id);
tag.TagTypeViewModel = new DropDownListViewModel();
tag.TagTypeViewModel.Items = new List<SelectListItem>();
tag.TagTypeViewModel.Items.Add(new SelectListItem { Text = "None", Value = "-1" });
tag.TagTypeViewModel.Items.AddRange(tagTypes
.Select(tt => new SelectListItem
{
Text = tt.Description,
Value = tt.Id.ToString(),
Selected = tt.Id == tag.TagType.Id
}).ToList());
return View(tag);
}
The select list has one element that has Selected=true, and it's not the first element.
And on my Edit.cshtml I have:
#model Models.Tag
#Html.DropDownListFor(model => model.TagTypeId,
#Model.TagTypeViewModel.Items,
new { #class = "form-control" })
My problem is that the generated drop down never selects the element that has Selected=true, it always shows the first element.
Am I calling the wrong overload for DropDownListFor? Or am I building the select list wrong? Or is it somethig else?
You should fill model.TagTypeId with selected TagTypeId in your Controller.
DropDownListFor selected value depends on first parameter value.
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.
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();
}