I'm attempting to, on the click of a button, complete a to-do item, therefore removing it from the list.
I'm using an ActionLink for the button:
#foreach (var item in Model)
{
<li class="#item.Priority">
#item.Text
<div class="agile-detail">
#Html.ActionLink("Done", "Complete", "Home", new { id = item.ToDoId }, new { #class = "pull-right btn btn-xs btn-primary" })
<i class="fa fa-clock-o"></i> #item.Date
</div>
</li>
}
And a very short action for the processing in the controller:
public ActionResult Complete(int todoId)
{
using (var db = new KnightOwlContext())
{
DashboardHelper dashboardHelper = new DashboardHelper(db);
dashboardHelper.CompleteToDo(todoId);
return RedirectToAction("Index", "Home");
}
}
Clicking the button generated a URL of:
http://site/Home/Complete/1
I've looked up a solution and so far it looks like it could be any number of issues. Also the ActionLink button is inside a partial view so I'm not sure if that changes anything in terms of incorrect routing setup? For routing too I'm just using the default config that comes with an MVC project in Visual Studio.
Just having trouble narrowing down the cause of the issue so where to check first?
The parameter in your method is int todoId but you not passing any value for that - your only passing a value for a parameter named id.
Change the method to
public ActionResult Complete(int id)
or change the link to use new { todoId = item.ToDoId }, but that will add a query string value, not a route value, unless you create a specific route definition with url: "Home/Complete/{todoId}"
Related
I have some problems with deletion item from database (SQLServer) using parameters for that. I want to press "Delete" reference in Index() then put name parameter in Delete() and redirect action to Index() again and show content of db. When I press "Delete" reference I show nothing but start page of Index() :(
public async Task<IActionResult> Delete(string nm)
{
IQueryable<Phone> users = db.Phones;
if (!String.IsNullOrEmpty(nm))
{
users = users.Where(p => p.Name.Contains(nm));
foreach (var item in users)
{
db.Phones.Remove(item);
}
await db.SaveChangesAsync();
}
return RedirectToAction("Index");
}
#model DataApp2.Models.Phone
#{
ViewBag.Title = "Delete";
}
<form method="get">
<div class="form-inline form-group">
<label class="control-label">Name: </label>
#Html.TextBox("nm", Model.Name, htmlAttributes: new { #class = "form-control" })
<input type="submit" value="Delete" class="btn btn-default" />
</div>
</form>
Building the input yourself and using a form is a bit overkill/overcomplicated. Instead, you can leverage the .NET MVC framework to send the request to your action
by replacing the form you posted and everything inside of it with:
#Html.ActionLink("Delete", "Delete", new { nm = Model.Name })
This will generate a link (<a> tag) with the text "Delete" (first param of the ActionLink) and send the Model.Name in a data field called nm to the Delete action in your controller (second param of the ActionLink).
I've put together a proof of concept showing that this works:
View:
#Html.ActionLink("Delete", "Delete", new { nm = "hi" })
Controller Action:
public ActionResult Delete(string nm)
{
if (!String.IsNullOrEmpty(nm))
{
ViewBag.Name = nm;
}
return RedirectToAction("Index");
}
the controller is successfully setting ViewBag.Name in this example. Note as far as the issue you're having, it makes no difference that I'm returning a ActionResult here instead of async Task<IActionResult> as you are.
I'm guessing that you're not populating Model.Name in the action that initially loads the page. Please post the code for your get action that loads the view if you'd like more information. You can test this theory by sticking:
#if (string.IsNullOrEmpty(Model.Name))
{
<h1>Name is empty!</h1>
}
else
{
<h1>Name is #Model.Name</h1>
}
in your view if you dont want to step through the code via the debugger
I have the following situation:
Into a view I define a link in this way:
<a href="#Url.Action("Edit", "Vulnerability", new { id = Model.Id })" data-mini="true" data-inline="true" data-role="button" >Annulla</a>
As you can see when the user click the link it is executed the Edit() method ot the VulnerabilityController class passing and Id value
Ok, this works fine but in this view I want have something like I have in a controller, this thing:
return new RedirectResult(Url.Action("Edit", "Vulnerability", new { id = vulnId }) + "#tab-2");
As you can see in this second version I always call the Edit() method of the VulnerabilityController class but the value of Id variable is something like "1234#tab-2"
Can I do something like this in my view and not only in my controller?
If you want to render (include) the results of some action inside your View you can use Html.Action:
#Html.Action("Edit", "Vulnerability", new { id = vulnId + "#tab-2" })
See MSDN
For doing this using Razor Syntax, you can try like this:
#Html.ActionLink("Annulla", "Edit", "Vulnerability", new { id = Model.Id },
new{ #data_mini="true", #data_inline="true", #data_role="button"})
My problem: drop down list at layout page.
I've read this post: ASP.NET MVC Razor pass model to layout it's more or less similar to my problem.
In one of comments Mattias Jakobsson wrote that: "But a common solution is to use RenderAction to render parts that need their own data in the layout page".
So ok I've created layout page with #Html.Action() that render my drop dwon list with a date from the db. Everything's perfect. But...
I have two pages, for example: 'Home', 'About' and my drop down list (ddl) at layout page
How to achive that when I'm at 'Home' and I changed selection in ddl it refresh 'Home' page and when I'm at 'About' it refresh 'About' page.
How to store selected ddl value through pages?
Part of Layout.cshtml code:
.
.
<body>
<header id="top" class="grid-full-margin">
<strong id="logo" class="grid-304"><img src="/images/logo.png" ></strong>
#Html.ActionLink(#Resources.Resource.BackToIntranet, "Index", "Home", null, new {#class = "link link-home grid-position-left"})
<h1>#Resources.Resource.SiteTitle</h1>
#Resources.Resource.LayoutHelp
<nav clss="grid-896">
<ul>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem1, "Index", "Home")</li>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem2, "Index", "ClimaticStation")</li>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem3, "Index", "ClimaticPoint")</li>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem4, "Index", "IcewaterExchanger")</li>
<li>#Html.ActionLink(Resources.Resource.LayoutMenuItem5, "Index", "Pipeline")
<ul>
<li>#Html.ActionLink("Zestawienie", "YearsLength", "Pipeline")</li>
</ul>
</li>
</ul>
<div class="mod-select-list tbl-actions">
#Html.Partial("~/Views/Shared/Partials/LoginPartial.cshtml")
</div>
</nav>
</header>
<form action="#">
#Html.Action("VariantsDdl", "MyBase")
</form>
#RenderBody()
.
.
Part of MyBaseController.cs
public class MyBaseController : Controller
{
[ChildActionOnly]
public ActionResult VariantsDdl()
{
var dataFromDb = GetDataFromDB(); // it's not importstn right now
return this.PartialView("~/Views/Shared/Partials/VariantsDdlPartial.cshtml", dataFromDb);
}
.
.
}
Regards,
Marcin
ok I've managed to solve this problem and I want to know your opinion abut my solution.
_Layout.cshtml looks the same way like at first post, so belowe is only most important part for this question (drop down list at layout)
<div style="float: right;">
#Html.Action("VariantsDdl", "MyBase")
</div>
Action: VariantsDdl is implemented at MyBaseController. This action loads selected variant id from session or if it's null then from web.config (in this situation it's project requirement that at least one variant must be present at db and its id must be specified in config):
[ChildActionOnly]
public ActionResult VariantsDdl()
{
long defaultVariantID;
long.TryParse(System.Configuration.ConfigurationManager.AppSettings["DefaultVariantId"], out defaultVariantID);
if (System.Web.HttpContext.Current.Session["mySelectedVariant"] != null)
{
long.TryParse(System.Web.HttpContext.Current.Session["mySelectedVariant"].ToString(), out defaultVariantID);
}
var variants = this.db.warianties.ToList();
var items = new List<SelectListItem>();
foreach (var variant in variants)
{
var selectedItem = false;
if(variant.id == defaultVariantID)
{
selectedItem = true;
}
items.Add(new SelectListItem { Selected = selectedItem, Text = variant.nazwa, Value = variant.id.ToString() });
}
return this.PartialView("~/Views/Shared/Partials/VariantsDdlPartial.cshtml", items);
}
Partial view and post action that stores selected variant id to session:
#model IEnumerable<SelectListItem>
<label for="field">Current variant</label>
#Html.DropDownList("Varaints", Model, new { id = "variantsDdl" })
<script type="text/javascript">
$(function () {
$('#variantsDdl').change(function () {
var val = $('#variantsDdl').val()
$.ajax({
type: "POST",
url: '#Url.Action("ChangeVariant", "MyBase")' + '/' + val,
success: function (result) {
location.reload();
},
error: function (data) { alert('Error'); }
});
});
});
Partial View post action 'ChangeVariant', saves selected variant id to session:
[HttpPost]
public ActionResult ChangeVariant(long id = 0)
{
System.Web.HttpContext.Current.Session["mySelectedVariant"] = id;
return null;
}
This is solution for my requirements:
1. DDL at layout
2. Refresh current page at DDL 'onchange'
3. Keep selected DDL value through pages
Please comment if it's appropriate solution or maybe should I go different way?
Regards,
Marcin
I am having some issues with MVC3 and Actionlink. I am dynamically building a HTML ActionLink using data passed from my model.
In the view:
#for (int i = 0; i < Model.CountriesList.Count; i++)
{
<li class="sub">#Html.ActionLink(Model.CountriesList[i].countryname,
"PageSub", new { PageID = Model.PageNo,
countryid = Model.CountriesList[i].countryid
})</li>
}
The Model.PageNo is passed from the controller and has a value. I have tested this. Every time I click on the link I am getting an error as the PageNo is not being passed as a parameter. The url outputs like below:
http://localhost/Pages/PageSub?countryid=196
I need it to be below which works when I directly enter it:
http://localhost/Pages/PageSub?PageID=136&countryid=196
This is my Controller ActionResult it directs to:
public ActionResult PageSub(int? PageID, int? countryid)
{
}
I have checked the code using developer tools and the link has been built as expected:
<li class="sub">
<a href="/Pages/PageSub?PageID=136&countryid=196">
</li>
Has anyone had similar issues? Any advice would be appreciated. Thanks
Try this:
#Html.ActionLink(Model.CountriesList[i].countryname, "PageSub", "Pages", new { PageID = Model.PageNo, countryid = Model.CountriesList[i].countryid }, null)
I am getting red x mark instead of the picture when storing in database. I believe I am having problems in the Views files. Please could someone have a look at this and tell me how to correct it. If I have wrong URL Actions please tell me which ones I should be using. Thanks in advance.
SubCategory2 Table has the following columns...
Column field > Picture1 : Data Type > varbinary(MAX)
Column field > ImageMimeType : Data Type > varchar(50)
Index.cshtml file
#foreach (var item in Model) {
<td>
<img src="#Url.Action("GetImage", "SubProductCategory2",
new { id = item.SubProductCategoryID})" alt="" height="100" width="100" />
</td>
Edit.cshtml file
"Edit" is the method in the contoller. "ProductCategoryL2" is the method in the controller. "GetImage" is the method in controller. All these methods are in the same controller file called ProductCategoryControllerL2
#using (Html.BeginForm("Edit", "ProductCategoryL2", "GetImage",
FormMethod.Post, new { #encType = "multipart/form-data" }))
{
<div class="editor-field">
<img src="#Url.Action("GetImage", "SubProductCategory2", new {
Model.SubProductCategoryID })" alt="" />
#Html.ValidationMessage("Picture1", "*")
<input type="file" id="fileUpload" name="Create" size="23"/>
</div>
}
ProductCategoryL2Controller.cs file
[HttpPost]
public ActionResult Edit(int id, FormCollection collection,
SubProductCategory2 editSubProdCat, HttpPostedFileBase image)
{
var r = db.SubProductCategory2.First(x => x.SubProductCategoryID
== id);
if (TryUpdateModel(r))
{
if (image != null)
{
editSubProdCat.ImageMimeType = image.ContentType;
editSubProdCat.Picture1 = new byte[image.ContentLength];
image.InputStream.Read(editSubProdCat.Picture1, 0,
image.ContentLength);
}
db.SaveChanges();
return RedirectToAction("/");
}
return View(r);
}
public FileContentResult GetImage(int productId)
{
var product = db.SubProductCategory2.First(x =>
x.SubProductCategoryID == productId);
return File(product.Picture1, product.ImageMimeType);
}
Addition Note
I am using MVC 3 framework. The GetImage method has been extacted from Steven Sanderson book Pro ASP.NET MVC 2 Framework. So I am not sure if that will be a problem?
The first step I would take to debug would be to try the URL for the image in your browser directly. Right-click on the red X, copy the url and paste it in your address bar. If the url looks right you should be a better error telling you what the problem is. If that fails, put a breakpoint in your GetImage routine to make sure the routes are correct and your method is getting called. Try Fiddler to see the request being made and what your web server is saying.
My guess is that you have the action wrong. It looks like you are linking to the GetImage action on the SubProductCategory2 controller when the method is on your ProductCategoryL2 controller.
Also I don't understand how your Model.SubProductCategoryID value is supposed to be mapped to your productId parameter. Try changing these calls:
Url.Action("GetImage", "SubProductCategory2",
new { id = item.ProductCategoryID})
Url.Action("GetImage", "SubProductCategory2", new {
Model.SubProductCategoryID })
to these:
Url.Action("GetImage", "ProductCategoryL2",
new { productId = item.ProductCategoryID})
Url.Action("GetImage", "ProductCategoryL2", new {
productId = Model.SubProductCategoryID })
Your input file field is called Create:
<input type="file" id="fileUpload" name="Create" size="23"/>
whereas the controller action parameter handling the form submission is called image (the one with HttpPostedFileBase type) => this parameter will always be null in your Edit controller action and nothing will be saved in the database.
Also the attribute is called enctype and not encType in the Html.BeginForm helper. Also inside the GetImage action ensure that product.Picture1 represents a correct image byte array and that it's content type matches with product.ImageMimeType.
So for example to further debug this issue you could try to save it to some temporary file to see if it is a valid image just before returning. Also make sure that the product instance you have fetched from the database is not null:
// if the content type is image/png:
File.WriteAllBytes(#"c:\foo.png", product.Picture1);
Then ensure that foo.png open successfully with an image viewer.
You are trying to return file content as the value to your img's src attribute. Your browser will need to issue a separate request for the image.
change your view to this:
<img src="GetImage/#(Model.SubProductCategoryID)" />