MVC4: How to send form parameter from view to controller? - asp.net-mvc

Browse action:
public ActionResult Browse(int? Category, string sortOrder, string currentFilter, string searchString, int? page)
I could send category id using action link
#Html.ActionLink("Name", "Browse", new { sortOrder = ViewBag.NameSortParm, currentFilter=ViewBag.CurrentFilter, Category=ViewBag.CategoryId })
How to pass category id from form to controller?
<div id="search">
#using (Html.BeginForm("Browse", "Home", FormMethod.Get))
{
#Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
}
</div>

You can send it in a hidden input:
#using (Html.BeginForm("Browse", "Home", FormMethod.Get))
{
#Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
#Html.Hidden("Category",ViewBag.CategoryId)
<input type="submit" value="Search" />
}

Related

Can't trigger my controllers action with a date time in the route values

Here is my form. If I remove the classdate parameter it works fine, but I can't trigger the controller if I have a date in the routevalues
using (Html.BeginForm("Results", "Home", new { classDate = DateTime.Now }, FormMethod.Get, new { #class = "navbar-form navbar-left", role = "search" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="navbarSearchQueryWithin" name="location">
</div>
<button type="submit" class="btn btn-default">Submit</button>
}
Here is my controller
[HttpGet]
public ActionResult Results(string navbarSearchQueryWithin, DateTime classDate)
{
var viewModel = new YogaSpaceListViewModel
{
SearchQuery = navbarSearchQueryWithin
};
return View("Search", viewModel);
}

how do I map my text box string into my url route?

I have a text box that I enter data into and pass with a post to my 'home' controller on action 'results'
I want the url to end up looking like this when I post back
https://localhost:44301/Home/Results/San Francisco, CA, United States
I'm passing the text box data like this.
#using (Html.BeginForm("Results", "Home", FormMethod.Get, new { #class = "navbar-form navbar-left", role = "search" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="navbarautocomplete" name="location">
<button type="submit" class="btn btn-default">Submit</button>
</div>
}
Here is my routing.
routes.MapRoute("SearchResults",
"home/results/{location}",
new { controller = "Home", action = "Results", location = ""}
);
How do I set my routing or my form to see the data that has been submitted as location in my url?
I can get it to look like this.
https://localhost:44301/home/results?location=San+Francisco%2C+CA%2C+United+States
but I want san francisco after /results/
As #StephenMuecke mentions in the comments, you could POST your search value to a (separate) action, then redirect to your results page, passing the location as a parameter:
#using (Html.BeginForm("Search", "Home", FormMethod.Post, new { #class = "navbar-form navbar-left", role = "search" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="navbarautocomplete" name="location">
<button type="submit" class="btn btn-default">Submit</button>
</div>
}
Then in your controller:
[HttpPost]
public ActionResult Search(string location)
{
return RedirectToAction("Results", new { location = location });
}
public ActionResult Results(string location)
{
return Content("location is: " + location);
}
You'll also to have the following route set up in your RouteConfig to get the friendly URL (make sure this is above the default route, as they match top-down).
routes.MapRoute(
name: "SearchResults",
url: "Home/Results/{location}",
defaults: new { controller = "Home", action = "Results" }
);

Html.BeginForm does not call action method in MVC

I have a partial view:
#model MsmStore.Domain.Products
<h3 class="lead">
#Model.Name
</h3>
#* <img src="~/images/MainLogo.jpg"/>*#
<p>
#Model.Decription
</p>
<p>
#Model.Price
</p>
#using (Html.BeginForm("UpdateBasketSummary", "Order", new { ProductID = Model.ID }))
{
#Html.Hidden("ProductID", Model.ID)
<input type="button" value="Click" />
}
this Html.BeginForm does not call action method (UpdateBasketSummary).
and this is my Action Method:
[HttpPost]
public PartialViewResult UpdateBasketSummary(string ProductID)
{
// orderRepository.AddToCart(ProductID, 1);
return PartialView("BasketSummary", ProductID);
}
this is my routing code:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(null, "{controller}/{action}");
An input with type button will not submit the form, by default. You need to change it to
<input type="submit" value="click" />
or
<button type="submit" value="click" />
Input of type button will not post your form, replace it with..
<input type="submit" value="Click" />
please, try this:
#using (Html.BeginForm("UpdateBasketSummary", "Order"))
{
#Html.Hidden("ProductID", Model.ID)
<input type="button" value="Click" />
}
[HttpPost]
public PartialViewResult UpdateBasketSummary(int ProductID)
{
//orderRepository.AddToCart(ProductID, 1);
return PartialView("BasketSummary", ProductID);
}
btw. not need to send ProductID in BeginForm, as you already did it by Hidden field
Edited: due to #Ben Griffiths answer:
you also need to change type='button' to type='submit' of course
Your action requires the http method POST and yet your beginForm call does not set the http method to POST. Without explicitly setting the http method you will be forced to use the default, which is a GET.

Multiple Action of Controller in single Button in MVC 4

my controller Have 2 Actions :
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}
//
// GET: /AdultLiteracyTeachers/Details/5
public ActionResult Details(int id = 0)
{
AdulLiteracyTeachers adulliteracyteachers = db.AdulLiteracyTeachers.Find(id);
if (adulliteracyteachers == null)
{
return HttpNotFound();
}
return View(adulliteracyteachers);
}
my view in Create.cshtml
#using (Html.BeginForm(Upload, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" }))
<input type="file" name="files" value="Upload Image" />
<input name="Upload" type="submit" value="Create" />
Problem is
only upload is working when I submit button others create etc not working
how to call multiple actions in single form create button ?
I believe you can use the beginform multiple times like this:
#using (Html.BeginForm(Upload, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" })){
<input type="submit" name="files" value="Upload Image" />
}
#using (Html.BeginForm(Details, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" })){
<input name="Upload" type="submit" value="Create" />
}
and make sure that the button type="submit".

How to pass other form data along with MVC File Upload?

I am trying to implement File Upload in MVC. I have the following code which works.
#using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="file" />
<input type="submit" value="OK" class="button" />
</div>
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
//do something here...
}
}
Now I want to add a dropdown box (to select the file type) and send that value along with the file to my Controller. How can I do that (send other form data along with the file)?
You should be able to add them to the view, include them in the POST and have MVC take care of the model binding:
#using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="file" />
<select name="fileType">
<option value="JPG">Photo</option>
<option value="DOC">Word</option>
</select>
<input type="submit" value="OK" class="button" />
</div>
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file, string fileType)
{
//Validate the fileType
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
//do something here...
}
}
I ended up doing it as follows it as follows. works good for me:
Created a Model:
public class FeeUpload
{
[Required (ErrorMessage="File Type required")]
public string fileType { get; set; }
[Required (ErrorMessage="file required")]
public HttpPostedFileBase File { get; set; }
}
View:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(false, "Please fix the following:")
<div>
<div>
#Html.DropDownListFor(model => model.fileType,
new List<SelectListItem>
{
new SelectListItem{ Text="xxx", Value = "yyy" },
new SelectListItem{ Text="xxx", Value = "yyy" },
new SelectListItem{ Text="xxx", Value = "yyy" }
}, "Select")
#*#Html.ValidationMessageFor(model => model.fileType)*#
</div>
<div>
#Html.TextBoxFor(model => model.File, new { type = "file" })
#*#Html.ValidationMessageFor(model => model.File)*#
<input type="submit" value="OK" class="button" id="btnsubmit" />
</div>
</div>
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FeesAndCostsUpload(FeeUpload feeUploadFile)
{
if (ModelState.IsValid)
{
//do something with feeUploadFile.File and feeUploadFile.fileType
}
return View();
}
Try to not use Razor for the form
<form method="POST" data-url="#Url.Action("Action", "Controller")" enctype="multipart/form-data">
#Html.ValidationSummary(true)
<span class="btn btn-success fileinput-button">
<i class="fa fa-plus"></i>
<span>Add a file...</span>
#Html.TextBoxFor(model => model.Fichier, new { type = "file" })
</span>
<div class="form-group form-actions">
<div class="col-sm-offset-3 col-sm-9">
<input id="submit" type="submit" class="btn btn-primary" value='Value' />
</div>
</div>
</form>
worked for me

Resources