I work on one of my first ASP MVC-programs at the moment.
The program should show me a list of product, and with a link beneath the name of the product it should be possible to edit the product. No problem so far.
#model MVC3Demo.Product
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm("Save", "Product"))
{
<div>
<input type="hidden" id="ID" name="ID" value="#Model.ID" />
ProduktID #Model.ID
</div>
<div>
Produktname <input id="Name" name="Name" type="text" value=#Model.Name />
</div>
<div>
Preis <input id="Price" name="Price" type="text" value=#Model.Price />
</div>
<div>
<input type="submit" value="Speichern"/>
</div>
}
Now I have written a Save action method that should update my data:
public ActionResult Save(Product p)
{
ProductRepository rep = new ProductRepository();
rep.Update(p);
return RedirectToAction("List");
}
The "List"-View is where I can see all products with the edit-link.
The problem is, that if I press the save-button, it redirects me to the old list, not to the updated one. I debugged my project and I´m sure that the update-method works correct and updates the product.
My List action is:
#model IEnumerable<MVC3Demo.Product>
#{
ViewBag.Title = "List";
}
<h2>List</h2>
<ul>
#foreach (MVC3Demo.Product p in Model)
{
<li>#p.Name #Html.ActionLink("bearbeiten", "Edit", "Product", p, null)</li> //new{ ID = p.id}
}
</ul>
Because you asked, here is the List Action:
public ActionResult List()
{
ProductRepository rep = new ProductRepository();
return View(rep.GetAll());
}
So where could be my mistake?
It looks like you're calling the update, but you're not actually submitting the transaction itself, does your repository have a SubmitChanges, AcceptChanges or Commit or something similar? As with DataTables, your changes won't actually take effect (save to the database) until you call AcceptChanges.
Try include an HttpPost attribute at Save controller method.
[HttpPost]
public ActionResult Save(Product p)
{
ProductRepository rep = new ProductRepository();
rep.Update(p);
return RedirectToAction("List");
}
Related
When the button is pressed it states that the model is invalid as fields are empty.
when looking at the model all fields are empty or null. anyone know how to solve this issue, thanks
Home Controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> createOrderLine(Product models)
{
if (ModelState.IsValid)
{
db.OrderLines.Add(new OrderLine
{
productId = models.productId,
productColour = models.productColour,
productDescription = models.productDescription,
productName = models.productName,
productPrice = models.productPrice,
productStock = models.productStock,
//QuantityOrdered = quantityOrdered
});
db.SaveChanges();
return RedirectToAction("Index", "OrderLines");
}
else return RedirectToAction("Index", "Home");
}
Home Index - Displays the product information to the screen
#foreach (var product in Model)
{
using (Html.BeginForm("createOrderLine", "Home", FormMethod.Post, new {
#class = "form-horizontal", role = "form" }))
{
<div class="row">
<div class="blog col-md-6">
<div>
<h1>Product Name</h1>
<h2>#product.productName</h2>
<div>
<h3>Product Description</h3>
<h6><i>#product.productDescription</i></h6>
<br />
<h3>Product Price</h3>
<td>#product.productPrice </td>
<br />
<h1>Product colour</h1>
<td>#product.productColour</td>
<div></div>
<br />
<br />
#Html.AntiForgeryToken()
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-buy" value="Add to cart" onclick="btnbuy_Click" />
</div>
</div>
</div>
</div>
<br />
</div>
</div>
}
}
the problem is that none of your field are linked to the model they only display it so to fix this
you can simply add a hiddenfor field that links the product id in your page like so for each of your product :
#Html.HiddenFor(product.Id)
then fill the rest of the informations you need with the id that is gonna be passed to your controller as a parameter
exemple :
public ActionResult createorderline(Product ProductToAdd)
{
// add your product or do your treatment
}
I do not quite understand what are you trying to do, but Louis is right. If you are trying to pass values back, you have to #Html.EditorFor() or some other ways to pass back information to the server.
You could also use #Html.HiddenFor(product.Id) then inside your Actionmethod call the database to get the rest of the info regarding your product or you could use JQuery as well.
In this case I would only use the #Html.HiddenFor(product.Id) and have a static helper method that will map your orderline class from the DB.
public static Product GetProductById(int productId){
return db.Products.FirstOrDefault(x => x.Id == productId);
}
But again you could just add the FirstOrDefault() line inside your controller as you not mapping from a ViewModel to a business Model.
I want to be able to select a few boxes and send the strings correlating to them. The problem however is that I don't know how to catch the values in the controller.
One important issue is that I do not want to bind it to a model! Hopefully you can help me find a solution that fits in this image
cshtml file:
#model IEnumerable<WebApplication1.Models.WikiPage>
#using (Html.BeginForm("DeletePages", "Home", FormMethod.Post))
{
<ul>
#foreach (var item in #Model)
{
<li>
#Html.CheckBox(item.Title)
#Html.Label(item.Title)
</li>
}
</ul>
<input type="submit" value="Delete pages" />
}
And here is the part in the controller. String... will be null and I don't know what I should put in there to catch the values
[HttpPost]
public ActionResult DeletePages(String... Titles)
{
removePages(Titles);
List<WikiPage> pages = db.WikiPages.ToList();
return View(pages);
}
Hope you can help me!
Kind regards
View:
#model IEnumerable<WebApplication1.Models.WikiPage>
#using (Html.BeginForm("DeletePages", "Home", FormMethod.Post))
{
<ul>
#foreach (var item in Model)
{
<li>
<label>#item.Title
<input type="checkbox" name="titles" value="#item.Title />
</label>
</li>
}
</ul>
<input type="submit" value="Delete pages" />
}
Controller:
[HttpPost]
public ActionResult DeletePages(string[] titles)
{
removePages(titles);
List<WikiPage> pages = db.WikiPages.ToList();
return View(pages);
}
I am using ASP.NET MVC with C# and pure bootstrap. One of my views contains a label, text input box, and a submit button:
#{
ViewBag.Title = "BinSearch";
Layout = "~/Views/Shared/_LayoutSearch.cshtml";
}
<h2>BinConfig Search</h2>
#using (Html.BeginForm("FiEdit", "EditConfigController"))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}
When I click the "submit" button, I would like to transfer the data to a controller, EditConfigController to this method:
[HttpPost]
public ActionResult FiEdit(int key)
{
return View(new IssuerKey().Key = key);
}
Which then is supposed to create a new view where I can edit data based off the key provided. This is the FiEdit view:
#model BinFiClient.Models.IssuerKey
#{
ViewBag.Title = "FiEdit";
Layout = "~/Views/Shared/_LayoutEdit.cshtml";
}
<h2>FiEdit</h2>
However, when I click the "submit" button, I receive a 404 error, and the URL path looks like this:
http://localhost:58725/EditConfigController/FiEdit
Which is actually the path to the method in the controller that I posted above.
What I need is basically a way to POST data to another controller. How can I accomplish this?
Edit:
Now I am receiving the error:
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'BinFiClient.Models.IssuerKey'.
Try replacing your code with the following:
#using (Html.BeginForm("FiEdit", "EditConfig", FormMethod.Post))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}
This will POST the parameter key to the EditConfig controller.
If you'd like to post to the action TestEdit in another controller, say the TestController, your code should be changed to the following:
#using (Html.BeginForm("TestEdit", "Test", FormMethod.Post))
...
To resolve the "model item passed into the dictionary" error, change your POST to be this:
[HttpPost]
public ActionResult FiEdit(int key)
{
return View(new IssuerKey() { Key = key });
}
ou can try with:
#using (Html.BeginForm(("FiEdit", "EditConfigController", FormMethod.Post,
new { enctype = "multipart/form-data" })))
{
<div class="form-group">
<label for="issuerKey">Issuer Key</label>
<input type="text" name="key" />
<input type="submit" class="btn btn-default" value="Search" />
</div>
}
I am new to asp.net MVC 4. i have some problems dealing with attributs
i use [httppost] attribut in my controller but it's not working
it's not even invoked
my controller
public ActionResult Inscription()
{
return View();
}
[HttpPost]
public ActionResult Inscription(Candidat candidat)
{
if (!ModelState.IsValid)
{
return View(candidat);
}
return RedirectToAction("Index");
}
my view
#model ProcRec.Models.Candidat
#{
ViewBag.Title = "Inscription";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.ValidationSummary(true)
<div class="form_settings">
#using (Html.BeginForm("Inscription", "CandidatController"))
{
<table ="#FFFFFF">
<tr>
<td>#*<span >Nom :</span>*# #Html.LabelFor(model => model.nom_candidat)</td>
<td> #Html.TextBoxFor(model => model.nom_candidat)
#Html.ValidationMessageFor(Model => Model.nom_candidat)
.
.
</table>
}
<input type="submit" class="submit right" value="Inscription" />
think you for your help
Just correct beginform as :
#using (Html.BeginForm("Inscription", "CandidatController",FormMethod.Post))
{
........
<input type="submit" class="submit right" value="Inscription" />
}
Put submit button inside BeginForm() and give BeginForm() FormMethod as Post.
Thankzz..
Put your <submit> element inside the form:
#using (Html.BeginForm())
{
...
<input type="submit" class="submit right" value="Inscription" />
}
Don't need to change Html.BeginForm. By default it's POST.
Check : FormExtensions.BeginForm
Only issue is with the submit button, it should be inside form as mentioned in Andy Refuerzo's answer. Don't know why it is down-voted.
I'm going crazy on this... I've been trying to figure out how to use ajax to update a partial view for quite some time... I've got to be missing something simple and easy.
I'm in VS2012, MVC4.
First, I do have these bundles loaded:
#Styles.Render("~/css")
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/js" )
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
I have also tried to specify the unobtrusive script manually as well...
Then I have this in my view:
#using (Ajax.BeginForm("Index_AddGroup", new AjaxOptions { UpdateTargetId = "AddGroupList" }))
{
<div>
#Html.LabelFor(model => Model.NewGroups.GroupName)
</div>
<div>
#Html.DropDownListFor(model => Model.AllGroups.nSelectGroupID, Model.AllGroups.GroupList, "Select Group to Add")
<input type="submit" value="Add Group" />
</div>
}
Then I load a partial view:
<div id="AddGroupList">
#if(Model.Groups != null)
{
#Html.Partial("_AddGroups", Model.Groups);
}
</div>
In that partial view I do the following:
#model IEnumerable<MyApp.ViewModels.Group>
#{
ViewBag.Title = "Added Groups";
}
<h2>Groups to be Added</h2>
<table>
<tr>
<th>Group Name</th>
<th>Added until</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(model=>item.GroupName)</td>
<td>#Html.DisplayFor(model=>item.EndDate)</td>
</tr>
}
Controller:
[HttpPost]
public ActionResult Index_AddGroup(SearchedUser viewModel)
{
AddGroupsContext db = new AddGroupsContext();
Group NewGroup = new Group();
NewGroup.GroupName = "test";//viewModel.
db.Groups.Add(NewGroup);
db.SaveChanges();
return PartialView("_AddGroups", db.Groups);
}
I loaded up fiddler and clicked on the button but no request was being sent. Why isn't that javascript/ajax code running?
I think you need a submit button. try:
<input type="submit" value="Add Group" />
Also i think you will need to add a reference to as it doesn't look like it is included anywhere:
jquery.unobtrusive-ajax.js
I think you can get it through nuget if you dont have it already.
otherwise here is a script tag that includes a CDN link:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.js"></script>