Button Submit in MVC is not working as expected - asp.net-mvc

I have a submit button in index.cshtml page and when i click that button i need to go in another ActionResult server method.But it's not working.(not hitting to the server side method)
Html
#model IEnumerable<AAB.Domain.Items>
<!-- Featured Products -->
<div class="card-deck card-deck-product mt-3 mb-2 mb-sm-0">
#foreach (var item in Model)
{
<div class="card card-product" id="#item.ItemId">
<div class="card-body">
<button class="wishlist atw-demo " title="Added to wishlist"><i data-feather="heart"></i></button>
<img class="card-img-top" src="#item.ImageUrl" alt="Card image cap">
#item.ItemName
<div class="price"><span class="h5">Rs:#item.ItemPrice</span></div>
</div>
<div class="card-footer">
<input type="submit" class="btn btn-sm" id="#item.ItemId" value="Add to Cart" href="#Url.Action("AddNewItems","Home",new { ItemId=item.ItemId})"/>
</div>
</div>
}
</div>
Server side
[HttpPost]
public ActionResult AddNewItems(int ItemId)
{
// Some code here.
return PartialView("_PopCart", ItemId);
}

Surround your button with a tag.
<a href="#Url.Action("AddNewItems","Home",new { ItemId=item.ItemId})">
<input type="submit" class="btn btn-sm" id="#item.ItemId" value="Add to Cart" />
</a>

Related

Error passing between Model and ViewModel?

In the previous question "ASP .NET Core Repository Id Article passed in was changed to 0?" I did it successfully, but due to a conflict with the team on GitHub, I had to rewrite my code. However, when I run it, I have a transmission error between Model and ViewModel. What is this and how do I fix it? I don't change anything between my code.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditArticle(Article article)
{
if(!ModelState.IsValid)
{
return View(article);
}
if(!_studentRepository.EditArticle(article))
{
throw new ArgumentException("...");
}
return RedirectToAction("Index");
}
View
#model Megatron.ViewModels.ArticleFacultyViewModel
#{
ViewData["Title"] = "Edit Article";
}
<div>
<form asp-action="EditArticle">
<partial name="_StatusMessage" model="#ViewData["Message"]" />
<div>
#Html.HiddenFor(a => a.Article.Id)
<div class="form-group row">
<div class="col-2">
<label asp-for="Article.Title" class="col-form-label"></label>
</div>
<div class="col-5">
<input asp-for="Article.Title" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label class="col-form-label">Type of contribution</label>
</div>
<div class="col-3">
<button hidden class="btn btn-primary" type="button" data-toggle="collapse" data-target="#ImportFileCollapse" aria-expanded="false" aria-controls="ImportFileCollapse">
</button>
<button hidden class="btn btn-primary" type="button" data-toggle="collapse" data-target="#TextAreaCollapse" aria-expanded="false" aria-controls="TextAreaCollapse">
</button>
<button id="button-collapse" class="btn btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls="ImportFileCollapse TextAreaCollapse">
Switch to Editor
</button>
</div>
</div>
You return a Artical type model to the View in the post method,
if(!ModelState.IsValid)
{
return View(article);
}
While the view expect a
ArticleFacultyViewModel type model. You may convert it.
if(!ModelState.IsValid)
{
var articleVM = new ArticleFacultyViewModel
{
Article = article,
Faculties = _facultyRepository.GetFaculties()
};
return View(articleVM);
}

Remove records from database using Entity Framework

I am trying to remove records from database using Entity Framework.
This is the code:
Controller:
[HttpPost]
public ActionResult DeleteProduct(int?id)
{
Product prd = db.Products.Find(id);
db.Products.Remove(prd);
db.SaveChanges();
return View();
}
View:
<form method="post" enctype="multipart/form-data">
<div class="row ">
#foreach (var product in Model)
{
<div class="col-md-6 col-lg-4 Products">
<figure class="card card-product mehsul">
<div class="img-wrap"> <img class="img-fluid mehsulimg" src="#product.PhotoProducts.First().ImageName" alt=""> </div>
<div class="handhover">
<img class="img-fluid" src="#product.PhotoProducts.Last().ImageName" alt="">
</div>
<figcaption class="info-wrap">
#product.ProdName
<p class="desc">Some small description goes here</p>
</figcaption>
<div class="bottom-wrap">
Paylash
<a id="DelProd" href="/ProductAd/DeleteProduct/#product.id" class="m-2 btn btn-sm btn-primary float-right">Sil</a>
<div class="price-wrap h5">
<span class="price-new">$1280</span> <del class="price-old">$1980</del>
</div> <!-- price-wrap.// -->
</div> <!-- bottom-wrap.// -->
</figure>
</div> <!-- col // -->
}
</div>
</form>
But I am getting this error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /ProductAd/DeleteProduct/1
If You are sending a delete request, it is not a [HTTPPost] and you are passing the whole model to the controller not only the key, so if you need to add id in your request, you should do something like this.
API Version:
[HttpDelete("{id}")]
public ActionResult DeleteProduct(int?id)
{
Product prd = db.Products.Find(id);
db.Products.Remove(prd);
db.SaveChanges();
return View();
}
Or using something like this for MVC Version with full model
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(YourViewModel viewModel)
{
var id = viewModel.id;
Product prd = db.Products.Find(id);
db.Products.Remove(prd);
db.SaveChanges();
return View();
}
Since your action has the "HttpPost" attribute, you need to do an HTTP POST. Your a tag would only do a GET, and the server would reject it as a page not found. Assuming everything else is correct, then I think it would be something more like this:
<div class="row ">
#foreach (var product in Model)
{
<div class="col-md-6 col-lg-4 Products">
<figure class="card card-product mehsul">
<div class="img-wrap"> <img class="img-fluid mehsulimg" src="#product.PhotoProducts.First().ImageName" alt=""> </div>
<div class="handhover">
<img class="img-fluid" src="#product.PhotoProducts.Last().ImageName" alt="">
</div>
<figcaption class="info-wrap">
#product.ProdName
<p class="desc">Some small description goes here</p>
</figcaption>
<div class="bottom-wrap">
Paylash
<form method="post" action="#Url.Action("DeleteProduct","ProductAd", new {id=productid})">
<button type="submit" class="m-2 btn btn-sm btn-primary float-right">Sil</a>
</form>
// or
#using(Html.BeginForm("DeleteProduct","ProductAd",new {id=product.id}))
{
<button type="submit" class="m-2 btn btn-sm btn-primary float-right">Sil</a>
}
<div class="price-wrap h5">
<span class="price-new">$1280</span>
<del class="price-old">$1980</del>
</div> <!-- price-wrap.// -->
</div> <!-- bottom-wrap.// -->
</figure>
</div> <!-- col // -->
}
</div>

Show or Hide History in MVC

I am working on a registration form. I want to show and hide my users past registrations using a button.The button should only show or hide registrations that are gone not the upcoming ones This is what I have so far. Pleasssseeee Help.
<div class="Table01">
<button id="older">Show Registration History</button>
#foreach (var sm in Model)
{
var tmp = #sm.SeminarNm.Replace("&", "and");
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 well table-item" align="left" data-toggle="tooltip" data-eventtype="#tmp" data-placement="top" title="#tmp">
<span class="sortName mid-weight"> #sm.SeminarNm</span>
<span class="sortDate alert-info">(ON #string.Format("{0:yyyy-MM-dd}", #sm.SessionStartDT) IN #sm.SessionCityNm)</span>
<div class="row " style="margin-top:10px">
#if (#sm.IsEditable == "Y")
{
using (Html.BeginForm("EditRegister", "App", FormMethod.Post, new { onclick = "showPageLoadingSpinner()" }))
{ #Html.AntiForgeryToken()
<div class="col-xs-12 col-md-6 col-lg-6">
<input class="btn btn-success " name="submitButton" type="submit" value="Edit" />
<input type="hidden" value="#sm.RegistrantSeq" name="hiddenseq" />
<input type="hidden" value="0" name="cntView" />
<input type="hidden" value="EditRegister" name="cntStage" />
</div>
}
}
#using (Html.BeginForm("ViewRegister", "App", FormMethod.Post))
{ #Html.AntiForgeryToken()
<div class="col-xs-12 col-md-6 col-lg-6 col">
<input class="btn btn-info" name="submitButton" type="submit" value="View" />
<input type="hidden" value="#sm.RegistrantSeq" name="hiddenseq" />
<input type="hidden" value="ViewRegister" name="cntStage" />
</div>
}
//
</div>
}
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script>
var $btns = $('.btn').click(function () {
if (this.id == 'older') {
$('#child > div').toggle(450);
}
$btns.removeClass('active');
$(this).addClass('active');
})
</script>
My Program Pic
I dont know if I need some sorting javascript function to display only those sessions that are in the past. Nothing seems to be working.
Assuming old registrations are any item with SessionStartDT value earlier than current date, you can set an html data attribute on each item's container div indicating whether it is an old item or new item and when user clicks the hide/show button, toggle the visibility of these items.
#foreach (var sm in Model)
{
<div data-old="#(p.SessionStartDT.Date < DateTime.Today.Date)">
<!-- your existing code for rendering each item goes here -->
</div>
}
And in the javascript part, when the button is clicked, make select the elements who's data-old attribute value is True (which we set via our C# expression which results in a boolean value) and toggle the visibility.
$(document).ready(function() {
$("#older").click(function(e) {
e.preventDefault();
$("[data-old='True']").toggle();
});
});

getting null value for HttpPostedFileBase in mvc controller

I want to give user the option to change their profile picture.On hitting the save button my controller action is hit but I get null value for HttpPostedFileBase.I am uploading files first time in mvc so not able to figure out where I am doing wrong and hence getting null value in controller.
controller
[AuthenticationRequired]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeProfilePicture(HttpPostedFileBase imageData)
{
}
view
#using (Ajax.BeginForm("ChangeProfilePicture", "Account", new { enctype = "multipart/form-data" },new AjaxOptions { OnSuccess = "OnSuccess" }))
{
#Html.AntiForgeryToken()
<div class="modal-body" id="tilesDescription">
<div class="row">
<div class="col-md-12">
<div class="text-center">
<div class="fileUpload btn btn-primary">
<span>Select a photo from your computer</span>
<input id="uploadBtn" type="file" class="upload" name="imageData" accept="image/*" />
</div>
<div class="text-center">
<img id="imgprvw" alt="uploaded image preview" class="imgPreview hide" />
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-rounded btn-sm btn-tiles" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-rounded btn-sm btn-tiles disabled" id="btnProfilePic">Set as profile picture</button>
</div>
}
You cannot post your file using ajax like that, cause is not supported.
From my experience, the easiest way to get files posted using Ajax (if using jquery), is using :
http://malsup.com/jquery/form/

File Upload using recent Bootstrap file upload and mvc asp.net

I looked over some other answers and the solutions there were not working. And I couldn't seem to figure out why. This is using Bootstrap 3.0. All I am trying to do is use that to upload a new avatar image. The problem is it always comes up null and I cannot seem to figure out why.
Here is my HTML:
#using (Html.BeginForm("EditAvatar", "Profile", new { userID = #Model.ProPit_User.userID }, FormMethod.Post, new { }))
{
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="" />
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
</div>
<div>
<span class="btn default btn-file">
<span class="fileinput-new">Select image
</span>
<span class="fileinput-exists">Change
</span>
<input id="avatar_image" type="file" name="..." runat="server">
</span>
<a href="#" class="btn default fileinput-exists" data-dismiss="fileinput">Remove
</a>
</div>
</div>
<div class="clearfix margin-top-10">
<span class="label label-danger">NOTE!
</span>
<span>Attached image thumbnail is supported in Latest Firefox, Chrome, Opera, Safari and Internet Explorer 10 only
</span>
</div>
</div>
<div class="margin-top-10">
<button type="submit" class="btn green">
Save Changes
</button>
<button type="reset" class="btn default">Cancel</button>
</div>
}
I have given the file input the ID of avatar_image
Here is the controller:
[HttpPost]
public ActionResult EditAvatar(HtmlInputFile avatar_image)
{
if (avatar_image.PostedFile != null)
{
//do whatever you want with the file
}
return View();
}
When looking at the break point the avatar_image.PostedFile is always null. Anyone have any idea what I am missing?
You might check the request in Fiddler. More importantly though, you need to add the enctype="multipart/form-data" attribute to the form.

Resources