Get Model back in Post - asp.net-mvc

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
}

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:

ASP.NET MVC - IHtmlFormElement's GetSubmission returns null

I'm making a POST request through an MVC controller using ASP.NET MVC and while unit testing I'm getting 'Object reference not set to an instance of an Object' from an IHtmlFormElement's GetSubmission() method. The test finds the button and the button itself is not null, but when the test calls the GetSubmission() with the submit button as a parameter it returns null.
Everything works fine from browser.
This is my Add.cshtml file content:
#model MVCPhones.Data.Phone
<form method="post" asp-action="Add">
<div class="form-group">
<label asp-for="Make" class="control-label">Make</label>
<input asp-for="Make" type="text" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Model" class="control-label">Model</label>
<input asp-for="Model" type="text" class="form-control" />
</div>
<div class="form-group">
<label asp-for="RAM" class="control-label">RAM</label>
<input asp-for="RAM" type="number" class="form-control" />
</div>
<div class="form-group">
<label asp-for="PublishDate" class="control-label">PublishDate</label>
<input asp-for="PublishDate" type="date" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Here is my PhonesController post method:
public async Task<IActionResult> Add(Phone phone)
{
try
{
phone.Created = DateTime.Now;
phone.Modified = DateTime.Now;
await _context.Phones.AddAsync(phone);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
Here is the section that gives the error:
Error

Asp.Net MVC - Data permutator

I have searched for hours for this without finding an answer, so I'm asking your help (I'm a beginner in web development (and in Asp.Net MVC)).
I want to create a simple data permutator (for example you enter 3 datas "a, b, and c", and I give you the possible permutations between these 3 datas : "abc; acb; bac; bca; cab; cba").
I have tried the following code, but it does not work (I have an HTTP 404 error).
<form method="post">
<div class="col-md-4 input-group">
<div class="input-group-addon">1</div>
<input type="text" name="firstData" class="form-control" placeholder="First Data" maxlength="50" required />
</div>
<div class="col-md-4 input-group">
<div class="input-group-addon">2</div>
<input type="text" name="secondData" class="form-control" placeholder="Second Data" maxlength="50" required />
</div>
<div class="col-md-4 input-group">
<div class="input-group-addon">3</div>
<input type="text" name="thirdData" class="form-control" placeholder="Third Data" maxlength="50" required />
</div>
<div class="col-md-12 mainAction centerbloc">
<input type="submit" value="Permutate the data" class="btn btn-success register-button-slider" href="">
</div>
</form>
And then below, I want to display the result in the same page, like this :
#{ if (IsPost)
{
string firstdata = Request.Form["firstData"];
string seconddata = Request.Form["secondData"];
string thirddata = Request.Form["thirdData"];
<p>
#firstdata #seconddata #thirddata<br />
#seconddata #firstdata #thirddata<br />
</p>
}
}
I haven't put anything special in my controller (maybe the mistake is here?) :
namespace Blogs.Controllers
{
public class ToolsController : Controller
{
[Route("tools/datapermutator", Name = "DataPermutator"), HttpGet]
public ActionResult DataPermutator()
{
return View();
}
}
}
If you have a way to do it, it would be very helpful, thank you in advance!

Best way to prevent HTML Code in Textbox MVC Razor View

I have following code on my view.
This HTML code is used for search in website.
This view is not strongly typed view, so I can apply use DataAnnotation through model.
What is best view to validate that, this textbox should accept only alpha numeric characters?
HTML
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" placeholder="search" class="fullwidth" onkeypress="return BlockingHtml(this,event);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
Javascript
function BlockingHtml(txt) {
txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r.]+/g, '');
}
Model:-
[StringLength(100)]
[Display(Description = "Name")]
[RegularExpression("(/[^a-zA-Z 0-9\n\r.]+/g", ErrorMessage = "Enter only alphabets and numbers of Name")]
public string Name{ get; set; }
Updated:-
View:-
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" id="txt" placeholder="search" class="fullwidth" onkeypress="BlockingHtml(this);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
function BlockingHtml(txt) {
txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r.]+/g, '');
}
<form action="Search" method="post" >
<div class="col-md-8">
<input type="text" name="name" placeholder="search" class="fullwidth" onblur="return BlockingHtml(this,event);" />
</div>
<div class="col-md-4">
<input type="submit" title="Search" value="Search" />
</div>
</form>
Changed event onkeypress to onblur.

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

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");
}

Resources