HttpPostedFileBase could not be found Visual studio 2019 - asp.net-mvc

hi,
i'm working on a asp.net core mvc with visual studio 2019,
(see attached for the mvc version (3.1.8).
i want to use HttpPostedFileBase, but getting error could not be found,
i've seen a solution suggesting to add using system.Web, and i did, but still getting this error,
Any ideas?
Edit:
Created the html :
<div class="col-md-6">
<div>
<input id="CSVFile" type="file">
</div>
<button onclick="Submit()">submit</button>
</div>
and javascript:
<script type="text/javascript">
function Submit() {
var pdata = new FormData();
var files = $("#CSVFile").get(0).files;
window.alert(files.Length);
pdata.append('CSVFile', files[0]);
$.ajax({
url: "Index",
type: "POST",
data: pdata,
processData: false,
contentType: false,
success: function (data) {
var input = $("#CSVFile");
input.replaceWith(input.val('').clone(true));
}
});
}
</script>
but the controller is not being called (it is defined HttpPost)
public ActionResult Index(IFormFile CSVFile)
{
return View();
}

.net core 3.1 doesn't contain HttpPostedFileBase.If you want to upload files,you can use IFormFile,here is an official tutorial.
Here is a simple demo to use IFormFile(from view to controller):
view:
<div class="row">
<div class="col-md-6">
<div>
<input id="CertImageFile" type="file">
</div>
<button onclick="Submit()">submit</button>
</div>
</div>
#section scripts{
<script type="text/javascript">
function Submit() {
var pdata = new FormData();
var files = $("#CertImageFile").get(0).files;
pdata.append('CertImageFile', files[0]);
$.ajax({
url: "Submit",
type: "POST",
data: pdata,
processData: false,
contentType: false,
success: function (data) {
var input = $("#CertImageFile");
input.replaceWith(input.val('').clone(true));
}
});
}
</script>
}
Controller:
[HttpGet]
public IActionResult TestIFormFile()
{
return View();
}
[HttpPost]
public IActionResult Submit(IFormFile CertImageFile)
{
return Ok();
}
result:

Related

Button click data-bind is not working with knockout

I cannot get the following piece of code to fire the button click to call save. I am using ASP.Net MVC with Knockoutjs. I am new to knockout and mvc. What am I missing here? Thanks in advance.
cshtml
#section scripts
{
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/CustomScripts/bookingviewmodel.js"></script>
<script type="text/javascript">
var bookingViewModel = new BookingViewModel(#Html.Raw(data));
ko.applyBindings(bookingViewModel);
</script>
}
<div class="content">
<button class="btn btn-primary pull-right" data-bind="click: save"><i class="fa fa-check"></i> Save Booking</button>
</div>
bookingviewmodel.js
BookingViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.save = function () {
$.ajax({
url: "/Booking/Save",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data) {
if (data.bookingViewModel != null) {
ko.mapping.fromJS(data.bookingViewModel, {}, self);
}
}
});
}
}

MVC partial in modal posting wrong model

My partial view which is loaded into a bootstrap partial on my Index page, should be posting type Announcement but is posting type AnnouncementViewModel of the Index page model to the Create controller.
The #modal-container is specified in my _Layout, which is working as expected.
Unsure about the controllers - they appear correct, the problem is stemming from my ajax post I believe but I don't know what's the issue. I get the error after POST, however the database does update with the model correctly, but afterwards I get the below error.
I have specified $('#create-container')/$('form') as the form in which to serialize and send back to the controller.
Why is it doing this?
Error:
The model item passed into the dictionary is of type 'AnnouncementsViewModel', but this dictionary requires a model item of type 'Announcement'.
Index:
#model AnnouncementsViewModel
<h2>Announcements</h2>
<div>
#Html.ActionLink("Create", "Create", "Announcements", null, new { #class = "modal-link btn btn-sm" })
<div class="announcementTable">
<div id="announcementList">
#{Html.RenderPartial("List", Model.AnnouncementList);}
</div>
</div>
</div>
Partial:
#model Announcement
#section Scripts {
<script type="text/javascript">
$(function () {
$('#btn-create').click(function () {
$.ajax({
url: '#Url.Action("Create","Announcements")',
type: 'POST',
contentType: 'application/json',
data: $('#create-container').serialize(),
success: function (data) {
if (data.success == true) {
$('#modal-container').modal('hide');
location.reload(false)
} else {
$('#modal-container').html(data);
}
}
})
});
$('#btn-close').click(function () {
$('#modal-container').modal('hide');
});
});
</script>
}
<div class="create-container">
#using (Html.BeginForm())
{
<div class="newAnnouncementTableRow1">
<div>#Html.LabelFor(m => m.Title)</div>
<div>#Html.EditorFor(m => m.Title)</div>
<div>#Html.LabelFor(m => m.Details)</div>
<div>#Html.EditorFor(m => m.Details)</div>
</div>
<div class="newAnnouncementTableRow2">
<div>#Html.LabelFor(m => m.StartDT)</div>
<div>#Html.EditorFor(m => m.StartDT)</div>
<div>#Html.LabelFor(m => m.ExpiryDT)</div>
<div>#Html.EditorFor(m => m.ExpiryDT)</div>
<div>#Html.LabelFor(m => m.Enabled)</div>
<div>
#Html.RadioButtonFor(m => m.Enabled, 1)Yes
#Html.RadioButtonFor(m => m.Enabled, 0, new { #checked = "checked" })No
</div>
</div>
<div>
<button type="submit" id="btn-create" class="btn btn-sm">Save</button>
<button type="button" class="btn btn-default modal-close-btn" data-dissmiss="modal">Cancel</button>
</div>
}
</div>
Controller:
[HttpGet]
public ActionResult Index()
{
var avm = new AnnouncementsViewModel
{
AnnouncementList = new List<Announcement>()
};
avm.AnnouncementList = GetAnnouncementList();
return View(avm);
}
[HttpGet]
public ActionResult Create()
{
return PartialView("Create");
}
[HttpPost]
public ActionResult Create(Announcement a)
{
db.DbAnnouncement.Add(a);
db.SaveChanges();
return Index();
}
You set contentType: 'application/json' it your .ajax() call but returning View from Controller. Either change contentType to html or change controller to return JsonResult and return Json("yourData");
I recommend you to change your ajax call:
$.ajax({
/* other data */
dataType : "html",
contentType: "application/json; charset=utf-8",
/* other data */
success: function (data) {
$('#modal-container').modal('hide');
location.reload(false)
},
error: function (jqXHR, textStatus, errorThrown )
{
$('#modal-container').html(data);
}
/* other data */
});
Thing is response from server in your case always success but it returns html rather than json so you just don't have data.success at all.
The other issue as mentioned in the comments was that the controller was redirecting to an action method that it could not.
Changing return Index(); to return RedirectToAction("Index", "Announcements"); solved the error and the redirecting to the Create partial page caused by using return View();.

Parameter passed from view to controller not working

I have a very simple view and can't figure out why my textbox value is not passing to my controller. Will the actionlink work for providing the controller the parameter?
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("LookupEmployee", "Home")) {
<div class="jumbotron">
<h2>Personnel System</h2><br />
<p>ID: <input type="text" id=employeeID name="employeeID" /></p>
#Html.ActionLink("Your Leave Balance", "LeaveBalance", "Home", null, new { #class = "btn btn-primary btn-large" })
</div>
}
<div class="row">
</div>
My HomeController takes the parameter and fills the dataset. I have hard coded a value and verified that this code works:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LeaveBalance(string employeeID)
{
//ViewBag.Message = "Your application description page.";
if (!String.IsNullOrEmpty(employeeID))
{
DataSet gotData;
LeaveRequestWCF myDataModel = new LeaveRequestWCF();
gotData = myDataModel.GetTheData(Convert.ToInt32(employeeID));
myDataModel.theModelSet = gotData;
return View(myDataModel);
}
return View();
}
}
Any advice? As you can tell, I'm new with MVC and trying to drift away from web forms.
OPTION 1:
You are using Html.ActionLink to post a form, which cannot be done because Html.ActionLinks are rendered as Anchor tags. Anchor tags make GET Requests unless we explicitly handle their JQuery click event. Use a Submit button to post a form for an appropriate controller action. So instead of -
#Html.ActionLink("Your Leave Balance", "LeaveBalance", "Home", null,
new { #class = "btn btn-primary btn-large" })
go for -
<input type="submit" class="SomeClass" value="Submit" />
OPTION 2:
You can also use AJAX POST using JQuery click event for anchor tag to post the form and once you get the result, you can make a client side redirection.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("#solTitle a").click(function() {
var data = {
"Id": $("#TextId").val()
};
$.ajax({
type: "POST",
url: "http://localhost:23133/api/values",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
// handle redirection here
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
});
</script>
ActionLink creates a simple <a href /> on the page, that will send a get request to the server.
You need a submit button instead, so your form gets posted with its form inputs. Use:
<button type="submit">Your Leave Balance</button>

MS MVC (razor) Access view data for serializartion

I have a view within a MS MVC [razor] project where I want to submit view data back to a controller via a JSON post operation. I have looked around and I cannot find how to retrieve and package the view data for submission back to the controller. I was under the assumption that the JSON serialize operation would package the data when called but this does not seem to be happening. For example:
MVC View ------------------------------
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<center>
<fieldset id="UserCreateFieldset">
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<p>
<input type="button" name="CreateButton" value="Create" onclick="CreateUser()" />
</p>
</fieldset>
</center>
}
<script>
function CreateUser()
{
var infoForm = $("#UserCreateFieldset");
var entries = infoForm.serializer.Serialize(Model);
$.ajax(
{
url: '#Url.Action("CreateUser", "User")',
data: entries,
type: "POST",
dataType: "json",
success: function (data)
{
$.event.trigger({
type: "CreateUserCompleted",
NewUserID: 1,
});
}
});
}
</script>
Just to note; when the controller is called via the post it receives back the model -- but it contains the original values used to load the view.
Peter
Use the .serialize() method from jquery:
function CreateUser()
{
var data = $('form').serialize();
$.ajax({
url: '#Url.Action("CreateUser", "User")',
data: data,
type: "POST",
dataType: "json",
success: function (data)
{
$.event.trigger({
type: "CreateUserCompleted",
NewUserID: 1,
});
}
});
}
You can instead of using Html.BeginForm use Ajax.BeginForm to not mess with the internals if you are doing the same thing as a the Html.BeginForm without anything special. you could change your code to:
#using(Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
HttpMethod = "POST"
}))
{
// Same form
}
It even has OnSuccess method which can be used in the AjaxOptions declaration:
#using(Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "TriggerEvent"
}))
{
// Same form
}
And you set a function in the javascript to be called on success:
function TriggerEvent() {
$.event.trigger({
type: "CreateUserCompleted",
NewUserID: 1,
});
}

Jquery sortable index change to ASP.NET MVC controller

I am trying to get the model binder to recognize the change. I am not sure what I am missing here. Basically the initial page population pulls the page number from the database. I then have the sortable working, the raw HTML in Firebug shows the change in order. But when I post back to the model first off it is not figuring out to go the post method and the other issue is Survey. Pages does not seem to have the change in order.
View
#for (var i = 0; i < Model.Pages.Count; i++)
{
var page = Model.Pages.ElementAt(i);
#Html.Hidden("Pages[" + i + "].PageId", page.PageId, new { #class = "page_index" })
#Html.Hidden("Pages[" + i + "].PageNumber", page.PageNumber)
<li id="#page.PageId" class="sortable-item text-center ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s">
</span>#page.PageNumber</li>
}
</ul>
JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('.sortable').sortable({
stop: function (event, ui) {
var formData = $('#editSurveryForm').serialize();
$.ajax({
url: "#Url.Action("Edit")",
data: formData,
type: 'POST',
traditional: true,
success: function () {
alert("success");
},
error: function () {
alert("fail");
}
}
);
}
});
});
</script>
Controller
[HttpPost]
public ActionResult Edit(Survey survey)
{
if (!ModelState.IsValid)
{
return View("EditSurvey", survey);
}
surveyRepository.UpdateSurvey(survey);
return RedirectToAction("Index", "Administration");
}
Ok, I figure this one out. I had the hidden fields outside of the <li></li> tag. Once I moved them inside I did all my logic as I would have.
<div class="span9">
<div class="span4">
<ul class="sortable_page_list">
#for (var i = 0; i < Model.Pages.Count; i++)
{
<li class="sortable-item text-center ui-state-default">
#Html.HiddenFor(model => model.Pages[i].PageId)
#Html.HiddenFor(model => model.Pages[i].PageNumber)
<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>#Model.Pages[i].PageNumber
</li>
}
</ul>
<div class="span1 pull-right internal-wrapper">
#Html.ActionLink("Add", "AddPage", new { id = Model.SurveyId }, new { #class = "add_survey_icon common_icon_settings" })
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.sortable_page_list').sortable({
update: function (event, ui) {
var counter = 1;
$("[id*='PageNumber']").each(function() {
$(this).attr("value", counter);
counter++;
});
//var surveyToUpdate = $('#editSurveyForm');
$.ajax({
url: '#Url.Action("Edit","Administration")',
contentType: "application/json; charset=utf-8",
data: $('#editSurveyForm').serialize(),
type: 'POST'
});
}
});
});
Last thing to figure out is why the ajax post is not posting to the Post method with the survey form data

Resources