Post action Create in asp.net MVC - asp.net-mvc

i'm using MS northwind database, and use Entity Framework.
I want to create new product, and use dropdownList to load CategoryName from Category Table.
public ActionResult Create()
{
var categories = from c in _en.Categories select c;
ViewData["CategoryID"] = new SelectList(categories, "CategoryID", "CategoryName");
return View();
}
<p>
<label for="ds">CategoryID:</label>
<%=Html.DropDownList("CategoryID", (SelectList)ViewData["CategoryID"])%>
</p>
Question: How to Save data from dropdownList?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "ProductID")] Products productToCreate)
{
if (!ModelState.IsValid)
return View();
var c = _en.Categories.FirstOrDefault(z => z.CategoryID == ??? XXXX ???);
productToCreate.Categories = c;
_en.AddToProducts(productToCreate);
_en.SaveChanges();
return RedirectToAction("Index");
}
how to get CategoryID from dropdownList?

Just add CategoryID to the arguments.
public ActionResult Create([Bind(Exclude = "ProductID")] Products productToCreate, string CategoryID)

Related

MVC Form DropDownListFor

In my view I am building a form where the user select a country from a list of Countries.I get this error about Object reference not set to an instance of an object. Is there anything I am missing?
#Html.DropDownListFor(
x => x.selectedCountryId,
new SelectList(Model.ListOfCountries, "Value", "Text"),
"-- please select a Country--",
new { id = "ddlCountry", #class = "form-control" }
)
#Html.ValidationMessageFor(x => x.selectedCountryId)
Model
[Required]
public int? selectedCountryId{ get; set; }
Error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Web.Mvc.WebViewPage<TModel>.Model.get returned null.
Action Method
public ActionResult Create(RequestFormViewModel model)
{
if (!ModelState.IsValid)
{
}
return View(TemplateName, "");
public ActionResult Index()
{
RequestFormViewModel result = new RequestFormViewModel ();
try
{
var FormInfo = GetFormInfo();
if (FormInfo != null)
{
result = FormInfo;
}
}
catch (Exception e)
{
}
return View(TemplateName, result);
}
Your action methods should be like below
[HttpGet]
public IActionResult Create()
{
//Way 1
RequestFormViewModel model = new RequestFormViewModel();
model.ListOfCountries = //Select from DB or Whatever
return View(model);
//Way 2
ViewBag.ListOfCountries = //Select from DB or Whatever
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(RequestFormViewModel model)
{
if (ModelState.IsValid)
{
}
return View(model);
}
and for view if you will use way 1 so you need to add ListOfCountries as [NotMapped] to your model or create Dto for this view
for way2 you need to bind dropdown from ViewBag instead of using ListOfCountries as a property

passing an id to Create of other model

In this actionLink I get the id from Cliente.
#Html.ActionLink("Pets", "Create", "Pets", new {id = Model.ClientId}, null)
Than i send this id to a view bag in PetController
public ActionResult Create(int id)
{
ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome");
return View();
}
But when a run the code, the dropdown show more than one Client.
As you can see in this image.
how can i show only de client who have the id that a i get in the actionlink ?
Thank's.
At Html
#Html.ActionLink("Pets", "Create", "Pets", new {id = Model.ClientId}, null)
At PetController
public ActionResult Create(int id)
{
ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome");
return View();
}

How to create a DropDownList from a LINQ query

I'm trying to use the results of a LINQ query to create a dropdownlist in an MVC app. I'm using this answer as a reference. However, when I try to implement for my case I get the error: 'System.String' does not contain a property with the name 'SAMPLING_EVENT'
My code is as follows:
Controller
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
ViewBag.Title = "Sample Tracker Tool";
DateTime nineMonthsAgo = DateTime.Now.AddDays(-270);
var context = new EDMS_Entities();
var resultSet = (from samplingEvents in context.EDMS_SAMPLES
where samplingEvents.RECORD_CREATED_DATE >= nineMonthsAgo
orderby samplingEvents.SAMPLING_EVENT
select samplingEvents.SAMPLE_ID)
.Distinct();
var viewModel = new SamplingEventsVM();
viewModel.SamplingEvents = new SelectList(resultSet, "SAMPLING_EVENT", "SAMPLING_EVENT");
return View(viewModel);
}
}
ViewModel class
public class SamplingEventsVM
{
public int SelectedSamplingEvent { get; set; }
public SelectList SamplingEvents { get; set; }
}
View
#model SamplingEventsVM
<h2>#ViewBag.Title</h2>
<span>
#Html.DropDownListFor(model => model.SelectedSamplingEvent, Model.SamplingEvents, "Sampling Event")
</span>
What am I doing wrong?
You are selecting this select samplingEvents.SAMPLE_ID
So you get a List of int maybe, depends on your ID type
Then you try to make a select list with the property value "SAMPLING_EVENT"
Which doesn't exist on the int object you filled resultSet with.
Instead do this:
var resultSet = (from samplingEvents in context.EDMS_SAMPLES
where samplingEvents.RECORD_CREATED_DATE >= nineMonthsAgo
orderby samplingEvents.SAMPLING_EVENT
select samplingEvents)
.Distinct();

How to get the selected checkbox value in post action in mvc 2

I have got a checkbox list populated from database , I want to get the ID of each checkbox list during post action so that I can save that in the db , Below is the Code :
Controller:
public ActionResult Create()
{
ITrackdayRepository trackdayResp = new TrackdayRepository();
IQueryable<Object> getAllEvents = trackdayResp.GetEventsSelectlist();
var m = new SelectList(getAllEvents,"ID","Name");
ViewData["events"] = new SelectList(getAllEvents.ToList(), "EventID","Date");
return View();
}
//
// POST: /Admin/Voucher/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// Get all the selected checkboxlist, do db insertion
return RedirectToAction("Index");
}
catch
{
return View();
}
}
View
<label>Events</label>
</td>
<td>
<% foreach (var item in (SelectList)ViewData["events"]) { %>
<input type="checkbox" name="Name" value="<%=item.Value %>" />
<label for="<%=item.Value%>"><%=item.Text%></label>
<br />
<% } %>
</td>
I want to pass selected <%=item.Value %> of the checkbox list to the post aqction of create , so that i can save it like 1,2,3,4 .
if you want to pass only the selected checkboxes when you post the form then do the following [as suggested]:
var myAnswers = collection["name"];
and then iterate through it and save it or you can try this way to
ASP.Net MVC List of Checkboxes
Its very simple . Use FormCollection in your Parameter list of Action method in your controller and then create a String Array for your CheckBoxBox values in your model .
Now Assign formvalue["Your_CheckBoxBox_value"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
to your newly created String Array in your Controller ........
public ActionResult Create()
{
ITrackdayRepository trackdayResp = new TrackdayRepository();
IQueryable<Object> getAllEvents = trackdayResp.GetEventsSelectlist();
var m = new SelectList(getAllEvents,"ID","Name");
ViewData["events"] = new SelectList(getAllEvents.ToList(), "EventID","Date");
return View();
}
//
// POST: /Admin/Voucher/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// Get all the selected checkboxlist, do db insertion
model.CheckBoxValues=collection["Your_CheckBox_valueOnView"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
all grouped checkboxes are returned as an array i.e 1,4,8 you just request
var myAnswers = collection["name"];
// split myAnswers here if required
in your code or am i missing something bigger here?
It's very simple, use FormCollection in your Parameter list of Action method in your controller and then create a String Array for your CheckBoxBox values in your model.
Now Assign
formvalue["Your_CheckBoxBox_value"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
to your newly created String Array in your Controller
public ActionResult Create()
{
ITrackdayRepository trackdayResp = new TrackdayRepository();
IQueryable<Object> getAllEvents = trackdayResp.GetEventsSelectlist();
var m = new SelectList(getAllEvents,"ID","Name");
ViewData["events"] = new SelectList(getAllEvents.ToList(), "EventID","Date");
return View();
}
// POST: /Admin/Voucher/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// Get all the selected checkboxlist, do db insertion
model.CheckBoxValues=collection["Your_CheckBox_valueOnView"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return RedirectToAction("Index");
}
catch
{
return View();
}
}

MVC Create a record issue

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")] ContentPageNav contentToCreate)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
ContentPageNav content = contentToCreate;
dc.SubmitChanges();
return RedirectToAction("Index");
}
What am I missing that the record is not getting inserted?
dc.ContentPageNavs.InsertOnSubmit(contentToCreate);

Resources