ASP.NET MVC2, can I use a model field as an html id? - asp.net-mvc

I am a newbie in ASP.NET and html.
I want to upload a file, so I have a model with a HttpPostedFileBase field, and a strongly-typed view that gets the model in order to get the value of the file.
My question is, how can I send to the controller the value of the file?
This is my html code, I'd like to send the value of File to Model.File, but placing <%:Model.File:> instead of file1 does not work :(
<label for="file1">File: </label>
<input type="file" name="file1" id="file1" size="40">
P.S.: I've also tried using the asp:FileUpload but I don't what how to send the result to the controller.
EDIT:
Ok, I go for posting my code, thank you very much ZeNo.
Here is the Model:
public class AddProductModel
{
[...]
public HttpPostedFileBase File { get; set; }
}
This is my View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Application.Models.AddProductModel>" %>
<form id="form1" runat="server">
<% using (Html.BeginForm()) { %>
<% Html.EnableClientValidation(); %>
<fieldset>
[...]
<div>
<label for="file1">File: </label>
<input type="file" name="file1" id="<%: Model.File %>" size="40">
<br />
</div>
<br />
<p>
<input type="submit" value="Add!" />
</p>
</fieldset>
<% } %>
</form>
Here is my controller, I use the debugger here and it says that model.File is empty:
[HttpPost]
public ActionResult AddProduct(AddProductModel model)
{
if (model.ProductName != null && model.ProductDescription != null)
objRepository.addToProducts(model);
return RedirectToAction("/AddProduct");
}

Use <%:Model.File %> instead.

put you file control inside a form tag
<form action="/Home/GetFile" id="myform">
<input type="file1" id="file1"/>
</form>
<script type="text/javascript" language="javascript">
var form = $("#myform");
form .submit();
</script>
controller:
[HttpPost]
public ActionResult GetFile(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
}
}

Change your view to:
<form action ="/AddProduct" id="myform">
<% Html.EnableClientValidation(); %>
<fieldset>
<div>
<label for="file1">File: </label>
<input type="file" name="file1" id="<%: Model.File %>" size="40">
<br />
</div>
<br />
<p>
<input type="submit" value="Add!" />
</p>
</fieldset>
</form>
notice I have removed form runat="server".. also there were nested forms..
add this Javascript snippet:
<script type="text/javascript" language="javascript">
var form = $("#myform");
form .submit();
</script>
in the controller make following changes:
[HttpPost]
public ActionResult AddProduct(HttpPostedFileBase file)
{
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
}
return RedirectToAction("/AddProduct");
}

Related

How to get Input control value in controller's Index method asp.net core

I am working on captcha authentication. I want to get user entered captcha value in controller's Index method. Below is my cshtml file code
#{
ViewData["Title"] = "Home Page";
}
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br/>
<button class="button" type="submit">Login</button>
<br />
</div>
When user entering captcha value in txtCapValue and click submit button I need that value in controller. Here is my controller
public IActionResult Index()
{
randnumber = RandomString(6);
ViewData["captcha"] = randnumber;
return View();
}
how can I get txtCapValue input control value when user click on submit button ?
One of the easy ways using the Form Tag Helper:
<form asp-controller="Controller_Name" asp-action="Captcha" method="post">
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button class="button" type="submit">Login</button>
<br />
</div>
</form>
And on the server side:
[HttpPost]
public IActionResult Captcha(string cap)
{
... using the `cap`
return View("Index");
}
I want to get user entered captcha value in controller's Index
method.
There are two options, you can try:
Option1: use Form Tag Helper
Index method:
public IActionResult Index(string cap)
{
ViewData["captcha"] = 6;//do your staff
return View();
}
Index view:
<form method="get" asp-action="Index">
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button class="button" type="submit">Login</button>
<br />
</div>
</form>
Option 2: use ajax
Index method:
public IActionResult Index(string cap)
{
ViewData["captcha"] = 6;
return View();
}
Index view:
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button id="buttonDemo1" class="button" type="submit">Login</button>
<br />
</div>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo1').click(function () {
var cap = $("#txtCapValue");
$.ajax({
type: 'GET',
url: '/Home/Index',
data: cap
});
});
});
</script>
}
result:

MVC foreach set item.ID to model.ID

I have a form that shows all the available hotel rooms, each room has a button that does a HttpPost if clicked, I have made a property in the BookingViewModel called 'RoomID'. I would like to assign the item.RoomID to Model.RoomID so I can use it in my controller to get the id from the selected room but i'm not sure how to achieve this.
ChooseRoom View
#foreach (var item in Model.AvailableRooms)
{
<li class="room-item clearfix">
<h5>#item.Name</h5>
<div class="room-list-left">
<img src="#item.Image" alt="" />
</div>
<div class="room-list-right">
<div class="room-meta">
<ul>
<li><span>Occupancy:</span> #item.Adults Adults #item.Childs Children</li>
#if (item.SmokingRoom)
{
<li><span>Smoking Allowed:</span> Yes</li>
}
else
{
<li><span>Smoking Allowed:</span> No</li>
}
</ul>
</div>
<div class="room-price">
<p class="price">From: <span>$#item.Price</span> / Night</p>
</div>
<div class="clearboth"></div>
#using (Html.BeginForm("chooseroom", "booking", FormMethod.Post))
{
<input class="button2" type="submit" value="Select Room" />
}
BookingController
[HttpPost]
public ActionResult ChooseRoom(BookingViewModel vm)
{
BookingViewModel bookingObj = GetBooking();
bookingObj.SelectedRoom = Repository.GetRoomByID(vm.RoomID);
return View("reservation", bookingObj);
}
Thank you for your time!
update your begin form as below
#using (Html.BeginForm("chooseroom", "booking", FormMethod.Post))
{
<input type="hidden" name="RoomId" value="#item.RoomID" />
<input class="button2" type="submit" value="Select Room" />
}
Just need to provide input tags having the same name as your ViewModel property.
You could add inputs in foreach loop , it should be inside form. Something like this <input name="Model.AvailableRooms[index].RoomID" value="Id Here"/>
Or if you want to select one Room you should use ajax and post id.
If I'm not wrong you form is in loop,so you could add hidden input with id
#Html.HiddenFor(c => c.AvailableRooms[index].RoomID)

Httppost not firing in mvc

I have two buttons on a page and I want the user to click one and they both go to different pages, the problem is my httpPost attribute is not firing.
Here is my controller:
public ActionResult Index()
{
if (Session["AccountConfirmationViewModel"] != null)
{
AccountConfirmationViewModel accountConfirmationViewModel = Session["AccountConfirmationViewModel"] as AccountConfirmationViewModel;
if (accountConfirmationViewModel == null || !TryValidateModel(accountConfirmationViewModel))
{
return RedirectToAction("AccountSearch", "Home");
}
MobileStep1ViewModel mobileModel = new MobileStep1ViewModel();
mobileModel.GetMobileNumbers(accountConfirmationViewModel.CustomerReferenceNumber);
Session["MobileModel"] = mobileModel;
}
return View();
}
[HttpPost]
public ActionResult Index(string button)
{
if (button == "btnNotMobileQuery")
{
RedirectToAction("AcconutSearch", "Home");
}
else if (button == "btnMobileQuery")
{
RedirectToAction("SecurityQuestion", "Mobile");
}
return View();
}
Here is my view:
#model OutsourcedTicketPlatform.UI.ViewModels.Mobile.MobileStep1ViewModel
#using OutsourcedTicketPlatform.UI.ViewModels.Mobile
#{
MobileStep1ViewModel mobileModel = Session["MobileModel"] as MobileStep1ViewModel;
ViewBag.Title = "Mobile Issue";
}
<h2>Mobile Issue Reporter</h2>
<p>Hi #mobileModel.CustomerName are you phoning today to log the mobile device as lost or stolen?</p>
#Html.RadioButton("IsMobileQuery", "MobileQuery")Yes
#Html.RadioButton("IsMobileQuery", "NotMobileQuery")No
<br /><br />
<div id="NotMobileQuery" class="HideDiv">
<input type="submit" class="btn" id="btnNotMobileQuery" value="Proceed" />
</div>
<div id="ConfirmMobile" class="HideDiv">
<p>"Please Confirm your mobile number"</p>
#foreach (var items in mobileModel.MobileNumbers)
{
#Html.RadioButton("SelectedMobileNumber", items)#items
}
<br /><br />
<input type="submit" class="btn" id="btnMobileQuery" value="Next" />
</div>
<script src="../../Scripts/Controllers/Mobile/MobileStepOne.js" type="text/javascript"></script>
<script src="../../Scripts/ViewModels/Mobile/MobileStepOneViewModel.js" type="text/javascript"></script>
Can anyone see if I am doing anything wrong? Do I need parameter in my second index method?
Try this :
#model OutsourcedTicketPlatform.UI.ViewModels.Mobile.MobileStep1ViewModel
#using OutsourcedTicketPlatform.UI.ViewModels.Mobile
#{
MobileStep1ViewModel mobileModel = Session["MobileModel"] as MobileStep1ViewModel;
ViewBag.Title = "Mobile Issue";
}
#using(Html.BeginForm("Index","Your_controller_name",FormMethod.Post)){
<h2>Mobile Issue Reporter</h2>
<p>Hi #mobileModel.CustomerName are you phoning today to log the mobile device as lost or stolen?</p>
#Html.RadioButton("IsMobileQuery", "MobileQuery")Yes
#Html.RadioButton("IsMobileQuery", "NotMobileQuery")No
<br /><br />
<div id="NotMobileQuery" class="HideDiv">
<input type="submit" class="btn" id="btnNotMobileQuery" value="Proceed" />
</div>
<div id="ConfirmMobile" class="HideDiv">
<p>"Please Confirm your mobile number"</p>
#foreach (var items in mobileModel.MobileNumbers)
{
#Html.RadioButton("SelectedMobileNumber", items)#items
}
<br /><br />
<input type="submit" class="btn" id="btnMobileQuery" value="Next" />
</div>
}
<script src="../../Scripts/Controllers/Mobile/MobileStepOne.js" type="text/javascript"></script>
<script src="../../Scripts/ViewModels/Mobile/MobileStepOneViewModel.js" type="text/javascript"></script>
You can use FormCollection instead of string for getting all values form view.

Why doesn't my List<string> bind to a series of hidden fields when using Html.Hidden()?

I'm trying to use the default model binder in asp.net mvc to bind a list of hidden fields
<input id="entity" name="entity" type="hidden" value="/string/one/here" />
<input id="entity" name="entity" type="hidden" value="/another/string/here" />
<input id="entity" name="entity" type="hidden" value="/last/string/here" />
To a List<string> like this:
[HttpPost]
public ActionResult Move(List<string> entity)
{
return View(entity);
}
When I post the form, the view displays the contents of the list like this:
<%foreach (string item in Model)
{%>
<%: Html.Hidden("entity", item)%>
<!--binding not working correctly -->
<%} %>
And the generated content is this:
<input id="entity" name="entity" type="hidden" value="/last/string/here" />
<input id="entity" name="entity" type="hidden" value="/last/string/here" />
<input id="entity" name="entity" type="hidden" value="/last/string/here" />
I'm confuseled. I tried changing the initial hidden field to this:
<input id="entity__" name="entity[]" type="hidden" value="/string/one/here" />
<input id="entity__" name="entity[]" type="hidden" value="/another/string/here" />
<input id="entity__" name="entity[]" type="hidden" value="/last/string/here" />
But when I tried posting that I got this error:
System.NullReferenceException: Object reference not set to an instance of an object.
on this line of code in the view:
<%foreach (string item in Model)
I've been able to bind list of strings before... without using an index in the name. I don't understand why this isn't working correctly. Maybe a fresh set of eyes could help me out with this?
Thanks
edit
In continuing to expirement. I ditched the HtmlHelper and hardcoded a hidden field inside the foreach loop like this:
<%foreach (string item in Model)
{%>
<input id="entity" name="entity" type="hidden" value="<%:item %>" />
<%} %>
This worked. I have no idea what the difference is between the Html helper's code and this so I put the two side by side and tried to match them up.
<input id="entity" name="entity" type="hidden" value="//Content/files/NewDirectory/Aesculuparviflora011cm.jpg" />
<input id="entity" name="entity" type="hidden" value="//Content/files/NewDirectory/Aesculuparviflora011cm.jpg" />
They are identical. But the binding works when I hardcode tags and it doesn't work when i use the html helper. What gives?????????
Why are you using loops and non-strongly typed helpers in a strongly typed view? Things could be so simple with editor templates:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new[]
{
"/string/one/here", "/another/string/here", "/last/string/here"
});
}
[HttpPost]
public ActionResult Index(List<string> items)
{
return View(items);
}
}
and the corresponding view (~/Views/Home/Index.aspx):
<%# Page
Title=""
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<string>>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%: Html.EditorForModel() %>
<input type="submit" value="OK" />
<% } %>
</asp:Content>
and the corresponding editor template (~/Views/Home/Index/EditorTemplates/string.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%: Html.HiddenFor(x => x) %>
Now you no longer need to worry about values not properly binding, writing loops in your views, ... you can finally concentrate on the real business logic of the application.
try:
<input id="entity" name="entity0" type="hidden" value="/last/string/here" />
<input id="entity" name="entity1" type="hidden" value="/last/string/here" />
<input id="entity" name="entity2" type="hidden" value="/last/string/here" />
I actually cannot recreate your problem:
This is my code, I tried fiddling with it and I cannot get it to malfunction.
perhaps check so that your view inherits the right type. Please post all of your code neccessary to make it malfunction.
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
var strings = new string[] { "test1", "test2", "test3" };
return View(strings);
}
[HttpPost]
public ActionResult Index(List<string> strings)
{
return View(strings);
}
aspx page
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<string>>" %>
<%using (Html.BeginForm()) { %>
<% foreach (var item in Model) { %>
<%:Html.Hidden("strings", item)%>
<% } %>
<input type="submit" value="Submit" />
<% } %>

Get Model back in Post

Is there any way to get information from my model during a result flagged HttpPost if I cannot pass it as a parameter?
[AcceptVerbs(HttpVerbs.Post)]
public FileUploadJsonResult Upload(HttpPostedFileBase file, IwantMyModelToo! )
I can't really get the actual view model to go through the method, though. Any thoughts?
Here is the primary view. (FoldersController)
<hr class="space" />
<div>
<% Html.RenderAction<Controllers.ImagesController>(i => i.Create(Model)); %>
</div>
<hr class="space" />
Here is the partial view (ImagesController, where the Create method resides)
// bunch of fun jQuery for jQuery Form Uploading.
</script>
<div class="span-24 last">
<fieldset>
<legend>Upload Image</legend>
<form id="ajaxUploadForm" action="<%= Url.Action("Upload", "Images")%>" method="post" enctype="multipart/form-data" >
<div>
<label for="file">Select Image</label><br />
<input type="file" name="file" />
</div>
<input id="ajaxUploadButton" type="submit" value="Upload" />
</form>
</fieldset>
</div>
In your code sample there are no properties connected to any model... Here I have added one (Foo) in a hidden form field, and created a class called MyModel.
View
<div class="span-24 last">
<fieldset>
<legend>Upload Image</legend>
<form id="ajaxUploadForm" action="<%= Url.Action("Upload", "Images")%>" method="post" enctype="multipart/form-data" >
<div>
<%= Html.Hidden("Foo", "bar") %>
</div>
<div>
<label for="file">Select Image</label><br />
<input type="file" name="file" />
</div>
<input id="ajaxUploadButton" type="submit" value="Upload" />
</form>
</fieldset>
</div>
Model
public class MyModel
{
public string Foo {get;set;}
}
Controller
public FileUploadJsonResult Upload(HttpPostedFileBase file, MyModel model)
{
//model.Foo should be accessible here
}

Resources