Ajax.BeginForm send parameters to controller - c#

I have following Ajax.BeginForm on viewpage
using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = #ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
<input type="file" name="files"> <input type="submit" value="Upload File to Server">
}
then I have following controller method in FileUpload controller class
[HttpPost]
public ActionResult Financing_Product_Feature_Upload(HttpPostedFileBase file, string productid)
{
but once I click above submit button its not directing to Financing_Product_Feature_Upload controller method

MVC serialization works on name attributes. Name of the form control needs to match with MVC controller action parameters. In your case, I guess, you should be getting an error in browser console when you hit "Submit" button saying "there is no matching action found on contoller FileUpload" or something which gives that meaning.
#using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = #ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="file" name="files"> <input type="submit" value="Upload File to Server">
}
public class FileUploadController : Controller
{
[HttpPost]
public ActionResult Financing_Product_Feature_Upload(HttpPostedFileBase files, string productid)
{
// Action code goes here
}
}

try add # in enctype
using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = #ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { #enctype = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
<input type="file" name="file"> <input type="submit" value="Upload File to Server">
}

Add # before using:
#using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
<input type="file" name="files"> <input type="submit" value="Upload File to Server">
}
And rename the HttpPostedFileBase file to files because this is your file input name.

Related

Submitting form with Dictionary model gets Controller name and Action name values-

I have a form that has a Dictionary<string, object> Model, When i submit the form values passed are Controller name and Action name. Why is this happening? Thank you in advance.
Here's my code:
Controller:
public ActionResult Form(int id)
{
var model = new Dictionary<string, object>();
model.Add("FullName", "Test");
model.Add("ContactNumber", "09973070562");
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(Dictionary<string, string> test)
{
return View("form", test);
}
Form:
#model Dictionary<string, object>
#{
ViewBag.Title = "Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<legend>Order</legend>
<br />
#using (#Html.BeginForm("save", "module", FormMethod.Post))
{
<fieldset>
#Html.AntiForgeryToken()
#foreach (var m in Model)
{
<div class="form-group">
<label>#m.Key</label>
<input type="text" class="form-control" name="#m.Key" value="#m.Value">
</div>
}
</fieldset>
<input type="submit" class="btn btn-primary" value="Submit">
}
you can use formdata in javascript.
then send it.
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
var formData = new FormData();
formData.append("FullName", "Groucho");
formData.append("ContactNumber", 123456);
var request = new XMLHttpRequest();
request.open("POST", "http://hamedhossani.com/Save");
request.send(formData);

Get text file as input in c# mvc

I want to get the text file as input but I am getting only null value...
public ActionResult add_content()
{
return View();
}
[HttpPost]
public ActionResult add_content(HttpPostedFileBase d)
{
return View();
}
HTML:
<form action="http://localhost:49416/g1/add_content" method="post">
<input type="file" name="d" />
<input type="submit" name=" add content" />
</form>
I have included the screenshot with breakpoint
You can try this:
Controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
return View();
}
View:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file"> Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
}
You were missing the enctype = "multipart/form-data"
Also it is important to note that input name must be the same in controller.

Sending a phrase (variable) from searcher (from view) to controller, asp.net mvc

I'm trying to create searcher in asp.net. I'm so green about it. I'm trying to create in view and send to controller variable, which has text written in searcher. In that moment, I have smth like that -->
My question is, where and how create and send variable and give her data written in searcher?
Layout
form class="navbar-form navbar-left" role="search">
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Wpisz frazę...">
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
</form>
Controller
public class SearcherController : ApplicationController
{
[HttpGet]
public ActionResult Index(string message)
{
ViewBag.phrase = message;
getCurrentUser();
return View();
}
}
View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<ul>
<li>#ViewBag.message</li>
</ul>
You're missing a key part of MVC -> the Model.
Let's create one first:
public class SearchModel
{
public string Criteria { get; set; }
}
Then let's update your "Layout" view (don't know why you had a form in a form?):
#model SearchModel
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
#Html.EditorFor(m => m.Criteria)
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
Then your action that serves that view:
[HttpGet]
public ActionResult Index()
{
return View(new SearchModel());
}
Then your post method would be:
[HttpPost]
public ActionResult Index(SearchModel model)
{
ViewBag.phrase = model.Criteria;
getCurrentUser();
return View();
}

Null Exception in File Uploading in MVC4 Razor

I have created the following view, with having file upload and submit button.
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" id="btnSubmit" />
}
I have also created the action method in Controller but it gives the null at the "uploadFile"
[HttpPost)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
Can u try Name with same as uploadFile
In your Page:
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="uploadFile" name="uploadFile" type="file" />
<input type="submit" value="Upload File" id="btnSubmit" />
}
As per #Willian Duarte comment : [HttpPost]
In your Code behind:
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile) // OR IEnumerable<HttpPostedFileBase> uploadFile
{
//For checking purpose
HttpPostedFileBase File = Request.Files["uploadFile"];
if (File != null)
{
//If this is True, then its Working.,
}
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
See here Same question like yours.,
Code project Article about the File upload.,
Try to use (on controller):
var file = System.Web.HttpContext.Current.Request.Files[0];
create a model and bind it to your view that controller will also expect:
Controller:
//Model (for instance I've created it inside controller, you can place it in model
public class uploadFile
{
public HttpPostedFileBase file{ get; set; }
}
//Action
public ActionResult Index(uploadFile uploadFile)
{
if (uploadFile.file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.file.FileName));
uploadFile.file.SaveAs(filePath);
}
return View();
}
View
#model sampleMVCApp.Controllers.HomeController.uploadFile
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.file, new { type = "file"});
<input type="submit" value="Upload File" id="btnSubmit" />
}
Tested Solution!
HTH :)
Use the following in the controller:
var file = System.Web.HttpContext.Current.Request.Files[0];
Use HttpPost instead of [AcceptVerbs(HttpVerbs.Post)]

Multiple Ajax.BeginForm on page

I need to implement multiple Ajax forms.
html
#using (Ajax.BeginForm("PerformAction", "Home", new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
<h3>This is a demo form #1.</h3>
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, null, new { #class = "labelItem" })
<input type="submit" value="Submit" />
}
<br />
<br />
#using (Ajax.BeginForm("PerformAction2", "Home", new AjaxOptions { OnSuccess = "OnSuccess2", OnFailure = "OnFailure2" }))
{
<h3>This is a demo form #2. </h3>
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, null, new { #class = "labelItem" })
<input type="submit" value="Submit" />
}
<br />
<br />
<script type="text/javascript">
function OnSuccess(response) {
alert(response);
}
function OnFailure2(response) {
alert("222 Whoops! That didn't go so well did it?");
}
function OnSuccess2(response) {
alert(response);
}
function OnFailure(response) {
alert("Whoops! That didn't go so well did it?");
}
</script>
C#
[AcceptVerbs("POST")]
public ActionResult PerformAction(FormCollection formCollection, Person model)
{
model.FirstName += " Form 1";
return View(model);
}
[AcceptVerbs("POST")]
public ActionResult PerformAction2(FormCollection formCollection, Person model)
{
model.FirstName += " Form 2";
return View(model);
}
But I am facing the error about that ASP .NET MVC 4 is looking for some kind of partial form.
I don't want to use any partial form and just I need to get working JavaScript OnSuccess and OnSuccess2
Any guess how it could be done?
Using View() or PartialView(), MVC it will try to find a view with a name equals to the action name.
So, just don't return a View(model)
Return a EmptyResult() or a JSON object.

Categories

Resources