Well, hello everyone.
I have a short ASP .NET MVC5 question. I have to pass a value from a ViewBag in the View method with a POST action result.
Create Method View Trigger
#Html.ActionLink("Add TestCase", "Create", "TestPlanTestCases", new { id = Model.TestPlan.ID }, null)
Controller Create GET method
public ActionResult Create(int id)
{
var testPlanFind = _db.TestPlan.Find(id);
ViewBag.TestPlanID = testPlanFind;
ViewBag.TestCaseID = new SelectList(_db.TestCase,"ID", "Name")
return View();
}
Create View, related DIV:
<div class="form-group">
#Html.LabelFor(model => model.TestPlanID, "TestPlanID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ViewBag.TestPlanID.Name
#Html.ValidationMessageFor(model => model.TestPlanID, "", new { #class = "text-danger" })
</div>
Controller Create POST method
public ActionResult Create([Bind(Include = "TestPlanID,TestCaseID")] TestPlanTestCases testPlanTestCases)
{
if (ModelState.IsValid)
{
_db.TestPlanTestCases.Add(testPlanTestCases);
_db.SaveChanges();
return RedirectToAction("Details", "TestPlans", new {id = testPlanTestCases.TestPlanID});
}
ViewBag.TestCaseID = new SelectList(_db.TestCase, "ID", "Name", testPlanTestCases.TestCaseID);
ViewBag.TestPlanID = new SelectList(_db.TestPlan, "ID", "Name", testPlanTestCases.TestPlanID);
return View(testPlanTestCases);
So, my problem is, when the POST method is being called, the method always receives TestPlanID = 0 and TestCaseID = (ID of the chosen test case). I've used the same workaround for a different controller that has similar functionality and it works perfectly fine, but for some reason, when it comes to setting a predefined value such as TestPlanID it is automatically being set to 0, not even a null. The GET method works fine and passes the right ID, but when it comes down to the POST method, something goes wrong.
I hope I have provided enough information for you to understand the issue.
Thanks in advance!
Well. I've finally solved it, maybe not the best solution, but it works.
A dev friend of mine suggested parsing the URL to get the ID in the POST method. So I've decided to add 3 additional lines of code to the controller, first one to parse the URL for ID value, second to convert the string to Int32, and then assign the result value to the testPlanTestCases.TestPlan.
Updated Controller:
public ActionResult Create([Bind(Include = "TestCaseID")] TestPlanTestCases testPlanTestCases)
{
var testPlanId = RouteData.Values["id"];
testPlanId = Convert.ToInt32(testPlanId);
testPlanTestCases.TestPlanID = (int) testPlanId;
if (ModelState.IsValid)
{
_db.TestPlanTestCases.Add(testPlanTestCases);
_db.SaveChanges();
return RedirectToAction("Details", "TestPlans", new {id = testPlanTestCases.TestPlanID});
}
ViewBag.TestCaseID = new SelectList(_db.TestCase, "ID", "Name", testPlanTestCases.TestCaseID);
ViewBag.TestPlanID = new SelectList(_db.TestPlan, "ID", "Name", testPlanTestCases.TestPlanID);
return View(testPlanTestCases);
Related
I created a simple CRUD using ASP.NET MVC and I can save my registers normally.
If I look in the Data Base my date was stored like that:
2017-06-01 00:01:23.750
But when I try to Edit the same register whith an async method created by MVC Scaffolding the date appears to bel null:
01/01/0001 00:00:00
Then (of course) I get an error:
The conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value.
Thats the async method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ArtigoId,Titulo,Texto,DataPublicacao,UltimaModificacao,UsuarioModificacao,DataCriacao,UsuarioCriacao")] Artigo artigo)
{
if (ModelState.IsValid)
{
db.Entry(artigo).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(artigo);
}
Why does it happen? How to correctly recover the date from data base?
EDIT:
I changed in Data Base for datetime2(0-7) but that made it accept the value 01/01/0001 00:00:00 and what I want is to know why this value appears instead of 2017-06-01 00:01:23.750.
All the others values in the data base is recovered normally, but not this date.
The problem occurred because I removed my field in the View and there is nothing to do with the date format in SQL Server.
I put the field back in the view as readyonly:
<div class="form-group">
#Html.LabelFor(model => model.DataCriacao, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataCriacao, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.DataCriacao, "", new { #class = "text-danger" })
</div>
</div>
The search of the field in the DB is done in the GET method:
// GET: Artigos/Edit/5
public async Task<ActionResult> Edit(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Artigo artigo = await db.Artigoes.FindAsync(id);
if (artigo == null)
{
return HttpNotFound();
}
return View(artigo);
}
The method I posted was POST after the submit of my button to save the changes and no searches were done on the database.
I created this simple ASP.NET project. (Default template using MVC)
In there I generated models from my database using ADO.net
I also generated controller for my model. (The model generated functions for create, edit, delete...) I also got view for every function in the controller.
So what I am trying to do now is:
-I am in my create view. (that means I see my form for creating objects)
-I need to enter data for [title, content] but to post in database I also need an id (this id is a foreign key, not the id of the object i am creating)
I already have this id saved in my session. I can access the session data by doing:
var user = Session["user"] as Uporabniki; //returns session data
user.id //selects id from session
Now what I want is to use this id in the create form textbox.
As of now the rows for id in my view look like this (I have no idea why it's a dropdown list. When I open the site I see names of all users in database and I can select one. But this is not what I want. I want to see only one):
<div class="form-group">
#Html.LabelFor(model => model.id_avtorja, "id_avtorja", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("id_avtorja", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.id_avtorja, "", new { #class = "text-danger" })
</div>
</div>
The create methods in controller look like this
// GET: Vprasanjas/Create
public ActionResult Create()
{
ViewBag.id_avtorja = new SelectList(db.Uporabniki, "id", "uporabniskoIme");
return View();
}
// POST: Vprasanjas/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,naslov,vsebina,datum,id_avtorja")] Vprasanja vprasanja)
{
if (ModelState.IsValid)
{
db.Vprasanja.Add(vprasanja);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.id_avtorja = new SelectList(db.Uporabniki, "id", "uporabniskoIme", vprasanja.id_avtorja);
return View(vprasanja);
}
Why is it not working if I change the view to something like this:
<div class="form-group">
#Html.LabelFor(model => model.id_avtorja, "id_avtorja", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#var user = Session["user"] as Uporabniki;
#Html.Raw(user.id)
#Html.ValidationMessageFor(model => model.id_avtorja, "", new { #class = "text-danger" })
</div>
</div>
And how can I fix this?
Try rewrite to
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,naslov,vsebina,datum,id_avtorja")] Vprasanja vprasanja)
{
if (ModelState.IsValid)
{
vprasanja.id = (Session["user"] as Uporabniki).id;
db.Vprasanja.Add(vprasanja);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.id_avtorja = new SelectList(db.Uporabniki, "id", "uporabniskoIme", vprasanja.id_avtorja);
return View(vprasanja);
}
Main idea - assign your id on post.
Please post some info on the error. But my guess is you aren't creating any input HTML element so there's nothing posting. You need something like <input type="hidden" id="id_avtorja" value="#user.id"> in the form.
Also, I'd advise against using data out of a session variable. That's older technology and very un-MVC in philosophy.
I have following GET method , that's a code to a create form
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct();
return View(sample);
}
this is the model class for that
public class AddNewProduct
{
public string Product_ID { get; set; }
...
}
this is that create form
#model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" }) <div class="form-group">
#Html.LabelFor(model => model.Product_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Product_ID, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Product_ID, "", new { #class = "text-danger" })
</div>
</div>
.....
<div>
#Html.ActionLink("Back to AddNewProduct", "AddNewProduct","Home" , new {Product_ID = Model.Product_ID})
</div>
}
I can Insert a Product_ID using this view page .But Once I click this Back to AddNewProduct link and debug AddNewProduct I cannot see any value for string Product_ID
Why this model properties not bind well
You need to assign value. Assign value of Product_ID which you are sending from get method to Product_ID property of class
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct();
sample.Product_ID = Product_ID;
return View(sample);
}
To pass the value of the textbox to the Add_Product() GET method, you need to use javascript/jquery. Replace you #Html.ActionLink(..) with
Back to AddNewProduct
and add the following script
var baseUrl = '#Url.Action("Add_Product", "Home")';
$('#back').click(function() {
var id = $('#Product_ID').val();
location.href = baseUrl + '/' + id;
}}
Note: location.href = baseUrl + '/' + id; assumes your have defined a specific route with {controller}/{action}/{Product_ID}, otherwise it needs to be
location.href = baseUrl + '?Product_ID=' + id;
Alternatively, change the method parameter to string id so it uses the default route
Note also that you will probably want to change the method to
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct
{
Product_ID = Product_ID
};
return View(sample);
}
so that if you click the Back to AddNewProduct link, the view will display the previous value you entered.
The second parameter of the #Html.ActionLink is the actionName but you sent the model name (AddNewProduct). Change it to this:
#Html.ActionLink("Back to AddNewProduct", "Add_Product","Home" , new {Product_ID = Model.Product_ID})
Or use this overload (You need to send null also when using this ActionLink overload):
#Html.ActionLink("Back to AddNewProduct", "Add_Product","Home" , new {Product_ID = Model.Product_ID}, null)
I am wondering if anyone could help me, the problem I have is that I am trying to not show the parameter in URL, when the parameter is posted to another controller. I have tried routing and changing the ActionLink. If anyone one could help it would be greatly appreciated.
I get "/Accounts/ViewCustomer/Index/3316", I want to hide 3316
Customer list view
#Html.Grid(Model.CustomerList).Columns(columns =>
{
columns.Add(data => data.Referance).Titled("Reference").Sanitized(false).Encoded(false).Filterable(true).
RenderValueAs(model => Html.ActionLink(model.Referance, "Index", "ViewCustomer",
routeValues: new { id = model.CustomerID },
htmlAttributes: new { id = "cust" }).ToHtmlString());
columns.Add(data => data.Company).Titled("Company").Sanitized(false).Encoded(false).Filterable(true).
RenderValueAs(model => Html.ActionLink(model.Company, "Index", "ViewCustomer", new { id = model.CustomerID }, null).ToHtmlString());
}).WithPaging(#ViewBag.Pagesize, #ViewBag.PageCountLimit).Sortable()
From view customer Controller to which int is posted
public ActionResult Index(int? id)
{
Paging paginginfo = GridPageProvider.Pagesize();
ViewData["Pagesize"] = paginginfo.Pagesize;
ViewData["PageCountLimit"] = paginginfo.PageCountLimit;
SetCustomerInfo(id);
if (_customerdetail.Contacts.Count != 0)
{
return View( _customerdetail);
}
else
{
return RedirectToAction("Index", "Home");
}
}
In this case 3316 is part of your URL and you can't hide it. But you can send id as parameter (you will need change routing) and use POST method to hide it in method body
I'm stuck here for over a week. I'm trying to create a dropdown list where when a user clicks on certain value from the dropdown list, it will redirect to another view called index. So below is my dropdown code. Values in the dropdown list is obtained from SQL Server. What do I do, should I change in controller, or in the view?
#Html.DropDownListFor(model => model.Reference, ViewBag.ISharedUI as SelectList, "-- REFERENCE TYPE --")
#Html.ValidationMessageFor(x => x.reftab)
thanks in advance.
edit:
by the way, below is the code in my controller in order to show the values for the dropdown
public ActionResult Create()
{
List<CommonEntities> ISharedUI = CommonDAL.GetARSharedReference();
ViewBag.ISharedUI = new SelectList(ISharedUI, "ID", "Description");
return View("Create");
}
//Here here here here here here
// POST: ListOfItems/Create
[HttpPost]
public ActionResult Create(ListOfItems objListOfItems)
{
try
{
// TODO: Add insert logic here
List<CommonEntities> ISharedUI = CommonDAL.GetARSharedReference();
ViewBag.ISharedUI = new SelectList(ISharedUI, "ID", "Description");
ListOfItems objListOfItemss = new ListOfItems();
objListOfItemss = ARSharedDAL.CreateARSharedInsert(objListOfItems);
return RedirectToAction("Index");
}
catch
{
List<CommonEntities> ISharedUI = CommonDAL.GetARSharedReference();
ViewBag.ISharedUI = new SelectList(ISharedUI, "ID", "Description");
return View();
}
}
You can use jQuery. Give the drop down list an id, like so.
<div id="FormDiv">
#using (Html.BeginForm("Create", "CONTROLLER", null, FormMethod.Post, new { }))
{
#Html.DropDownListFor(model => model.Reference, ViewBag.ISharedUI as SelectList, "-- REFERENCE TYPE --",new {id = "dblist" })
#Html.ValidationMessageFor(x => x.reftab)
}
</div>
Then use jQuery to submit its parent form
$('#dblist').on('change', function(event){
var form = $(event.target).parents('form');
form.submit();
});