Calling actionresult from view - asp.net-mvc

This is my ActionResult()
public ActionResult pay()
{
return View();
}
[HttpPost]
public ActionResult mytry()
{
return View();
}
and this is my view pay.chtml
#using (Html.BeginForm("mytry", "Home"))
{
<table>
<tr>
<td align="center">
<input type="button" value="submit" />
</td>
</tr>
</table>
}
I am not able to call the mytry() action result from here. How to do it?

In order to submit your form, you must use <input type="submit" /> or <button type="submit"> Try the following:
#using (Html.BeginForm("mytry", "Home", FormMethod.Post))
{
<table>
<tr>
<td align="center">
<input id="btnSubmit" type="submit" value="Submit" />
</td>
</tr>
</table>
}

Related

ASP .NET MVC: Get the url and view the image as it changes

I have a function that allows me to edit an image but I want as soon as I click the Edit button I will get the URL of the current image
image:
Do not see "no file chosen"
I want the URL of the image to appear on the right
Step Two Once I swap a picture I also want the picture to change to the picture I swap
My Service:
public class FileService : IFileService
{
private readonly IWebHostEnvironment _environment;
public FileService(IWebHostEnvironment environment)
{
_environment = environment;
}
public async Task<string> File([FromForm] CreateAnimalViewModel model)
{
string wwwPath = _environment.WebRootPath;
var path = Path.Combine(wwwPath, "Images", model.Photo!.FileName);
if (model.Photo.Length > 0)
{
using var stream = new FileStream(path, FileMode.Create);
await model.Photo.CopyToAsync(stream);
}
return model.Animal!.PhotoUrl = model.Photo.FileName;
}
public interface IFileService
{
Task<string> File([FromForm] CreateAnimalViewModel model);
}
My ViewModel:
public class CreateAnimalViewModel
{
public Animal? Animal { get; set; }
public IFormFile Photo { get; set; }
}
My Controller:
public async Task<IActionResult> EditAnimal(int id)
{
var animal = await _repo.FindAnimalById(id);
ViewBag.Category = new SelectList(_repository.GetCategoriesTable(), "CategoryId", "Name");
return View(new CreateAnimalViewModel() { Animal = animal});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditAnimal([FromForm] CreateAnimalViewModel model)
{
ModelState.Clear();
TryValidateModel(model);
await _file.File(model);
if (!ModelState.IsValid)
{
await _repo.EditAnimal(model.Animal!);
return RedirectToAction(nameof(Manager));
}
return View();
}
My Repository:
public async Task<int> AddAnimal(Animal animal)
{
_context.Add(animal!);
return await _context.SaveChangesAsync();
}
public async Task<int> EditAnimal(Animal animal)
{
_context.Update(animal);
return await _context.SaveChangesAsync();
}
public DbSet<Category> GetCategories()
{
var category = _context.Categories;
return category;
}
My View:
#model PetShop.Client.Models.CreateAnimalViewModel
<form asp-action="EditAnimal" method="post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly"></div><input type="hidden" asp-for="Animal!.AnimalId" id="Space"/>
<dl class="row" >
<dt class = "col-sm-2"><label asp-for="Animal!.Name" id="Space"></label></dt>
<dd class = "col-sm-10"><input asp-for="Animal!.Name"/><span asp-validation-for="Animal!.Name" id="Validation"></span></dd>
<dt class = "col-sm-2"><label asp-for="Animal!.BirthDate" id="Space"></label></dt>
<dd class = "col-sm-10"><input asp-for="Animal!.BirthDate"/><span asp-validation-for="Animal!.BirthDate" id="Validation"></span></dd>
<dt class = "col-sm-2"><label asp-for="Animal!.Description" id="Space"></label></dt>
<dd class = "col-sm-10"><input asp-for="Animal!.Description"/><span asp-validation-for="Animal!.Description"></span>
</dd> <dt class = "col-sm-2"><label asp-for="Animal!.CategoryId" id="Space"></label></dt>
<dd class = "col-sm-10"><select asp-for="Animal!.CategoryId"asp-items="ViewBag.Category"></select>
<span asp-validation-for="Animal!.CategoryId"></span></dd>
<dt class = "col-sm-2"><label asp-for="Photo"></label></dt>
<dd class = "col-sm-10"><input type="file" asp-for="Photo" accept="image/*"/>
<img src="~/images/#Model.Animal!.PhotoUrl"
class="rounded-square"
height="50" width="75"
style="border:1px"
asp-append-version="true" accept="image/*" />
<span asp-validation-for="Photo" id="ImageValidation"></span></dd>
<br /> <br /><br/><input type="submit" value="Save" id="ButtonDesign"/>
</dl>
</form>
<a asp-action="Commands"><input type="submit" value="Back to Admin Page" id="BackPageButton"/></a>
image:
You cannot implement that:
I have gone through your code what you are trying to implement is to set initial value on input type="file" which is not possible due to
security reasons which you can check here. In addition you can also have a look here thousands of questions been askedbefore. Note that it's against RFC standard.
What you can do is:
While loading the Edit page hide the <input type="file"
Set a checkbox beside photo and it URL like below:
If the checkbox clicked then show the "file upload" option.
Note: Elementary JavaScript required for that implementation.
HTML:
<div>
<form asp-action="EditAnimal" method="post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly"></div><input type="hidden" asp-for="Animal!.AnimalId" id="Space" />
<div>
<h4><strong>Animal Details</strong> </h4>
<table class="table table-sm table-bordered table-striped">
<tr>
<th> <label asp-for="Animal!.Name"></label></th>
<td> <input asp-for="Animal!.Name" class="form-control" placeholder="Enter animal name" /><span asp-validation-for="Animal!.Name"></span></td>
</tr>
<tr>
<th> <label asp-for="Animal!.Description"></label></th>
<td> <input asp-for="Animal!.Description" class="form-control" placeholder="Enter animal description" /><span asp-validation-for="Animal!.Description"></span></td>
</tr>
<tr>
<th> <label asp-for="Animal!.Category"></label></th>
<td> <input asp-for="Animal!.Category" class="form-control" placeholder="Enter animal category" /><span asp-validation-for="Animal!.Category"></span></td>
</tr>
<tr>
<th> <label asp-for="Photo"></label></th>
<td>
<img src="~/images/#Model.Animal!.PhotoUrl"
class="rounded-square"
height="50" width="75"
style="border:1px"
asp-append-version="true" accept="image/*" />
<span>#Model.ImageURL</span>
<input type="checkbox" id="CheckBoxId" class="form-check-input" style="margin-top:16px;border:1px solid" /> <span><strong>Upload New File</strong></span>
<input type="file" name="photo" id="chooseFile" accept="image/*" />
</td>
</tr>
<tr>
<th> <label>Updated On Local Time</label></th>
<td> <input asp-for="Animal!.LocalTime" class="form-control" disabled /><span asp-validation-for="Animal!.Category"></span></td>
</tr>
<tr>
<th> <button type="submit" class="btn btn-primary" style="width:107px">Update</button></th>
<td> </td>
</tr>
<tr>
<th>#Html.ActionLink("Back To List", "Index", new { /* id=item.PrimaryKey */ }, new { #class = "btn btn-success" })</th>
<td> </td>
</tr>
</table>
</div>
</form>
</div>
JavaScript:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
//On Edit Page Load Hiding the upload option
$("#chooseFile").hide();
//When upload check box clicked showing the upload option
$('#CheckBoxId').mousedown(function() {
if (!$(this).is(':checked')) {
this.checked = true;
$("#chooseFile").show();
}
else{
$("#chooseFile").hide();
}
});
});
</script>
}
Output:

mvc passing data from view to controller

My Controller
public class OgrenciController : Controller
{
[HttpPost]
public ActionResult home(int perId)
{
if(perId=="anything")
{
//something
}
return View();
}
}
This is my view
#foreach (var item in Model)
{
siraNo++;
<form method="post">
<input type="radio" name="perId" value="#item.specialId">
<input type="submit" value="send" />
</form>
}
but in the POST method, perId not take anythings
use something like this.
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<input type="radio" name="perId" value="#item.specialId"><br /><br />
}
<input type="submit" ur value="send" />
}

Sending table datas to Controller without using ajax

I have a table in view which is static in nature.I am trying to post data to Controller without using Jquery Ajax. Is it possible?How can I retrieve all these data in Action "bulk_insert". I am able to send this bulk data to controller using jquery ajax but I am unable to send it directly.
My view :
#using entity_framework.Models
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<h1>Static data</h1>
<div>
#using (Html.BeginForm("bulk_insert", "Form", FormMethod.Post, new { enctype = "multipart/form-data", id = "postForm" }))
{
<table id="myTable" class="table table-striped">
<thead>
<tr>
<td>Menu Item Id</td>
<td>Menu Item Name</td>
<td>Menu Qty</td>
<td>Menu Rate</td>
<td>Total</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="hidden" name="menu_item_id[0]" value="1" /><span>1</span></td>
<td><input type="hidden" name="menu_item_name[0]" value="chaumin" /><span>chaumin</span></td>
<td><input type="hidden" name="data[0].rate" value="100" /><span>100</span></td>
<td><input type="hidden" name="data[0].qty" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[0].total" value="200"><span>200</span></td>
</tr>
<tr>
<td><input type="hidden" name="data[1].menu_item_id" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[1].menu_item_name" value="Mo:Mo" /><span>Mo:Mo</span></td>
<td><input type="hidden" name="data[1].rate" value="100" /><span>100</span></td>
<td><input type="hidden" name="data[1].qty" value="2" /><span>2</span></td>
<td><input type="hidden" name="data[1].total" value="200"><span>200</span></td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" />
}
</div>
I am just testing with static data right now,but I need to do it with dynamic data i.e, When a user clicks a button, a row gets added using javascript .So,I didn't use Htmlhelper. My model:
public class tabledata
{
public int menu_item_id { get; set; }
public string menu_item_name { get; set; }
public string rate { get; set; }
public string qty { get; set; }
public string total { get; set; }
}
I don't know how can I get table datas from form but my Controller method:
[HttpPost]
public ActionResult bulk_insert(IEnumerable<tabledata> data)
{
//How can I get table datas here
}

Issue with mvc, partial view dispaying

I have a question about partial view. I want to display in header Login form which i created. In HomeController I have 2 actions: one is Login and other is Login with httppost method.
In partial view (_Layout.cshtml) I have a code - only send footer div:
<td style="text-align:center">
<h3>Bookstore</h3>
#Html.Partial("_LoginPartial")
</td>
In Login view I have:
#using(Html.BeginForm("Login", "Home", FormMethod.Post)){
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<table>
<tr>
<td>#Html.LabelFor(a=>a.Username)</td>
<td>#Html.TextBoxFor(a=>a.Username)</td>
<td>#Html.ValidationMessageFor(a=>a.Username)</td>
</tr>
<tr>
<td>#Html.LabelFor(a=>a.Password)</td>
<td>#Html.PasswordFor(a=>a.Password)</td>
<td>#Html.ValidationMessageFor(a=>a.Password)</td>
</tr>
<tr>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>}
Controller
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Users u)
{
if (ModelState.IsValid) {
using (DatabaseLoginEntities dl = new DatabaseLoginEntities()) {
var v = dl.Users.Where(a => a.Username.Equals(u.Username) && a.Password.Equals(u.Password)).FirstOrDefault();
if (v != null) {
Session["LogedUserId"] = v.UserAccountID.ToString();
Session["LogedUserFullName"] = v.FullName.ToString();
return RedirectToAction("AfterLogin");
}
}
}
return PartialView("_LoginPartial", u);
}
When press Login button, mvc switches me to separate page in which Login form is shown. I don't want that to happen. It must stay in header. Functionality is ok but I have issue how to show that only in header. Has anyone have idea where I'm wrong?
you must use ajax
#using (Ajax.BeginForm("Login", "Home",
new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace
,
UpdateTargetId = "div_id"
}
)){
<table>
<tr>
<td>#Html.LabelFor(a=>a.Username)</td>
<td>#Html.TextBoxFor(a=>a.Username)</td>
<td>#Html.ValidationMessageFor(a=>a.Username)</td>
</tr>
<tr>
<td>#Html.LabelFor(a=>a.Password)</td>
<td>#Html.PasswordFor(a=>a.Password)</td>
<td>#Html.ValidationMessageFor(a=>a.Password)</td>
</tr>
<tr>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>
}

How to Update Database on ButtonClick in ASP.NET MVC architecture

Hi i am looking to capture values from my view and update the entered values in to my database .
My view looks like following :
#using Kendo.Mvc.UI
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Facility</title>
</head>
<body>
<div>
<p>Create a new Facilty</p>
<table width="100px">
<tr>
<td>
<label for="TenantId">TenantID:</label>
</td>
<td>
<input id="TextTenantId" type="text" />
</td>
</tr>
<tr>
<td>
<label for="FacilityID">FacilityID:</label>
</td>
<td>
<input id="TextFacilityID" type="text" />
</td>
</tr>
<tr>
<td>
<label for="FacilityGroupID">FacilityGroupID:</label>
</td>
<td>
<input id="TextFacilityGroupID" type="text" />
</td>
</tr>
<tr>
<td>
<label for="FacilityName">FacilityName:</label>
</td>
<td>
<input id="TextFacilityName" type="text" />
</td>
</tr>
<tr>
<td>
<label for="FacilityAddressLine1">FacilityAddressLine1:</label>
</td>
<td>
<input id="TextFacilityAddressLine1" type="text" />
</td>
</tr>
<tr>
<td>
<label for="FacilityAddressLine2">FacilityAddressLine1:</label>
</td>
<td>
<input id="TextFacilityAddressLine2" type="text" />
</td>
</tr>
<tr>
<td>
<label for="FacilityAddressLine3">FacilityAddressLine1:</label>
</td>
<td>
<input id="TextFacilityAddressLine3" type="text" />
</td>
</tr>
<tr>
<td>
<label for="CityId">CityId:</label>
</td>
<td>
<input id="TextCityId" type="text" />
</td>
</tr>
<tr>
<td>
<label for="StateId">StateId:</label>
</td>
<td>
<input id="TextStateId" type="text" />
</td>
</tr>
<tr>
<td>
<label for="CountryId">CountryId:</label>
</td>
<td>
<input id="TextCountryId" type="text" />
</td>
</tr>
<tr>
<td>
<label for="Zipcode">Zipcode:</label>
</td>
<td>
<input id="TextZipcode" type="text" />
</td>
</tr>
<tr>
<td>
<label for="PhoneNo">PhoneNo:</label>
</td>
<td>
<input id="TextPhoneNo" type="text" />
</td>
</tr>
<tr>
<td>
<label for="Status">Status:</label>
</td>
<td>
<input id="TextStatus" type="text" />
</td>
</tr>
<tr>
<td>
<label for="EmailId">EmailId:</label>
</td>
<td>
<input id="TextEmailId" type="text" />
</td>
</tr>
<tr>
<td>
<label for="Website">Website:</label>
</td>
<td>
<input id="TextWebsite" type="text" />
</td>
</tr>
<tr>
<td>
<input id="Submit1" type="Submit" value="submit" />
</td>
</tr>
</table>
</div>
</body>
</html>
My model looks like :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AmanoMockUp.Models
{
public class FacilityModels
{
public int TenantId { get; set; }
public int FacilityId { get; set; }
public int FacilityGroupId { get; set; }
public string FacilityName { get; set; }
public string FacilityAddressLine1 { get; set; }
public string FacilityAddressLine2 { get; set; }
public string FacilityAddressLine3 { get; set; }
public int CityId { get; set; }
public int StateId { get; set; }
public int CountryId { get; set; }
public string Zipcode { get; set; }
public int PhoneNo { get; set; }
public bool status { get; set; }
public string EmailId { get; set; }
public string Website { get; set; }
public DateTime CreationDate { get; set; }
}
}
now i need to update the values entered in the view in the various textfields onto my database on the submission of my button
<input id="Submit1" type="Submit" value="submit" />
Where should i write the buttonclick event should it be on the controller or the model or should i create a whole new controller for the same .Please help !!
I have searched but i couldnt find anything related to my issue .
Thanx in advance !!
How about having your view strongly typed against your model and having the form submit the values to an action method that does the work? do some searching on Html.BeginForm for pointers on having a form call a specific action on submission and just about any basic MVC tutorial for strongly typing a view to a model.
database calls should be in the controller.
in the controller create another action with the [HttpPost] attribute but with the same name. it will take the model as its parameter. then complete the database logic and save changes and return the view.
look at the example here
http://www.c-sharpcorner.com/UploadFile/krishnasarala/select-insert-update-and-delete-with-Asp-Net-mvc/

Resources