I have simple controller with two actions:
public class TestController : Controller
{
// /Test
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
bool b = file == null; //there will be false
return RedirectToAction("Index");
}
// /Test/Wonder
[HttpGet]
public ActionResult Wonder()
{
return View();
}
[HttpPost]
public ActionResult Wonder(HttpPostedFile file)
{
bool b = file == null; //there will be TRUE!
return RedirectToAction("Wonder");
}
}
I have similar views for my actions.
Index action:
<h2>Index</h2>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
Wonder action:
<h2>It's wonder!</h2>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
Why does first form (Index) submit correct file to controller, but second form (Wonder) submits null to controller?
Your Index ActionResult receives as a parameter a HttpPostedFileBase object whereas the Wonder ActionResult receives as a parameter a HttpPostedFile object.
Related
I am trying to change the value on a screen after calling a post method. It seems even with the ModelState.Clear(); method added it still does not reflect the new value on the screen. Note that I am using jQuery Unobtrusive AJAX v3.2.6 library.
Please see my razor page and controller code below.
#model TestApp.ViewModels.EmployeeViewModel
<form method="post"
data-ajax="true"
data-ajax-method="post"
data-ajax-url="#Url.Action("Detail", "Employee")">
<input asp-for="EmployeeFirstName" />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Controller
public IActionResult Detail()
{
EmployeeViewModel employeeViewModel= new EmployeeViewModel ();
employeeViewModel.EmployeeFirstName = "John";
return View(employeeViewModel);
}
[HttpPost]
public IActionResult Detail(EmployeeViewModel employeeViewModel)
{
employeeViewModel.EmployeeFirstName = "Brian";
ModelState.Clear();
return View(employeeViewModel);
}
Since you use unobtrusive ajax,so it will return the html code of the partial view,but it will not refresh the partial view.If you want to refresh the partial view,you can try to replace the html code with data-ajax-complete.Here is a working demo:
Controller:
public IActionResult Detail()
{
EmployeeViewModel employeeViewModel = new EmployeeViewModel();
employeeViewModel.EmployeeFirstName = "John";
return View(employeeViewModel);
}
[HttpPost]
public IActionResult Detail(EmployeeViewModel employeeViewModel)
{
employeeViewModel.EmployeeFirstName = "Brian";
ModelState.Clear();
return PartialView("~/Views/_Partial.cshtml", employeeViewModel);
}
View:
#model WebApplication107.Models.EmployeeViewModel
<div class="row main-section-border">
<div id="div1" class="col-sm-12">
#{
await Html.RenderPartialAsync("~/Views/_Partial.cshtml", Model);
}
</div>
</div>
#section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js"></script>
<script>
completed = function (xhr) {
$("#div1").html(xhr.responseText);
};
</script>
}
_Partial view:
#model WebApplication107.Models.EmployeeViewModel
<form method="post"
data-ajax="true"
data-ajax-method="post"
data-ajax-url="#Url.Action("Detail", "Test")"
data-ajax-complete="completed"
>
<input asp-for="EmployeeFirstName" />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Result:
I have to pass hidden filed values to controller action. So I have tried in the following way, but I am getting null values.
I have tried both methods i.e formcollection and viewmodel concept
Controller
public ActionResult MapIcon()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult MapIcon(Hidden hidden)
{
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
View
#model SVGImageUpload.Models.Hidden
Razor view:#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Viewmodel
public class Hidden
{
public string hiddevalue { get; set; }
}
Try this, In Razor view:
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="submit" value="Match"/>
}
It seems to me like you are trying to get multiple values into the POST controller. In that case, and by your exam, the value from the hidden input is enough. In that case, you can setup your controller as so:
public ActionResult Index()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult Index(IEnumerable<string> hiddens)
{
foreach (var item in hiddens)
{
//do whatter with item
}
return View(new Hidden());
}
and as for your view, simple change it in order to bind to the same name "hiddens" as so:
#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" value="7" name="hiddens" />
<input type="hidden" value="2" name="hiddens" />
<input type="submit" value="Match" />
}
Hope this serves what you are looking forward to.
if your hidden value is static.Than try this
View
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Controller
[HttpPost]
public ActionResult MapIcon(Hidden hidden, string hidden1, string hidden2)
{
var hiddenvalue = hidden.hiddevalue;
var hiddenvalue1 = hidden1;
var hiddenvalue2 = hidden2;
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
Script
$(document).ready(function () {
$('#hiddevalue').val("Jaimin");
});
What are the ways to render the input value filename and send it to a controller :
<div id="fileuploaddiv" class="fileuploaddivclass">
<form action="#Model.FormAction" method="#Model.FormMethod"
enctype="#Model.FormEnclosureType">
<input type="hidden" name="key" value="uploads/${filename}" id="filename" />
<input type="hidden" name="AWSAccessKeyId" value="#Model.AWSAccessKey" />
<input type="hidden" name="Content-Type" value="image/jpeg">
<div>
Please specify a file, or a set of files:
<input type="file" name="file" />
</div>
<input type="submit" value="Upload" />
</form>
</div>
You need to look up some MVC3 conventions (I'd recommend NerdDinner as a good starting tutorial), but here is a somewhat similar approach to what you want to do:
#Model YourViewModel
<div id="fileuploaddiv" class="fileuploaddivclass">
#using(Html.BeginForm(Model.FormAction, Model.FormController, FormMethod.Post)
#Html.HiddenFor(model.key => ${fileName})
#Html.HiddenFor(model.AWSAccessKeyID)
#Html.HiddenFor(model.Content-Type)
#<input type="submit" value="Submit My Form" />
#Html.EndForm()
</div>
Your model would look like (And I'm confused here because you seem to be dynamically setting the controller and action, which is unusual):
public class YourViewModel
{
public string FormAction { get; set; }
public string FormController { get; set; }
public int AWSAccessKeyID { get; set; }
public string Content-Type { get; set; }
}
Now on to controllers:
[HttpGet]
public ActionResult WhateverControllerName()
{
YourViewModel yvm = new YourViewModel();
//Initalize viewmodel here
Return view(yvm);
}
[HttpPost]
public ActionResult WhateverControllerName(YourViewModel yvm)
{
if (ModelState.IsValid) {
//Do whatever you want here. Perhaps a redirect?
}
return View(yvm);
}
Note: I am garbage at syntax, so you'll have to check this, but Visual Studio should tell you what works.
Had this working; at one stage. The problem is the following text is now appearing in the field for the image in the database "System.Web.HttpPostedFileWrapper"
the following code is from the controller:
[HttpPost]
public ActionResult Create(CarAdvert caradvert,
HttpPostedFileBase picture1)
{
if (ModelState.IsValid)
{
if (picture1 != null)
{
string image1 = picture1.FileName;
caradvert.Image1 = image1;
var image1Path = Path.Combine(Server.MapPath("~/Content/Images"), image1);
picture1.SaveAs(image1Path);
}
db.CarAdverts.Add(caradvert);
db.SaveChanges();
return RedirectToAction("Index");
}
This code is from the create view:
#using (Html.BeginForm("Create", "UserCarAdverts", FormMethod.Post, new { enctype = "multipart/form-data" })) {
#Html.ValidationSummary(true)
<fieldset>
<legend>CarAdvert</legend>
<div class="editor-field">
<input type="file" name="Image1" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
the paramater in the controller for HttpPostedFileBase has to have the same name as the input type="file" . Either do:
[HttpPost]
public ActionResult Create(CarAdvert caradvert,
HttpPostedFileBase Image1)
or
<input type="file" name="picture1" />
That should do it
I have code in View:
#using (Html.BeginForm("MyAction", "MyController")
{
<input type="text" id="txt" />
<input type="image" src="/button_save.gif" alt="" />
}
How can I pass value of txt to my controller:
[HttpPost]
public ActionResult MyAction(string text)
{
//TODO something with text and return value...
}
Give your input a name and make sure it matches the action's parameter.
<input type="text" id="txt" name="txt" />
[HttpPost]
public ActionResult MyAction(string txt)
Add an input button inside of your form so you can submit it
<input type=submit />
In your controller you have three basic ways of getting this data
1. Get it as a parameter with the same name of your control
public ActionResult Index(string text)
{
}
OR
public ActionResult Index(FormsCollection collection)
{
//name your inputs something other than text of course : )
var value = collection["text"]
}
OR
public ActionResult Index(SomeModel model)
{
var yourTextVar = model.FormValue; //assuming your textbox was inappropriately named FormValue
}
I modified Microsoft MVC study "Movie" app by adding this code:
#*Index.cshtml*#
#using (Html.BeginForm("AddSingleMovie", "Movies"))
{
<br />
<span>please input name of the movie for quick adding: </span>
<input type="text" id="txt" name="Title" />
<input type="submit" />
}
//MoviesController.cs
[HttpPost]
public ActionResult AddSingleMovie(string Title)
{
var movie = new Movie();
movie.Title = Title;
movie.ReleaseDate = DateTime.Today;
movie.Genre = "unknown";
movie.Price = 3;
movie.Rating = "PG";
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Index");
}
}