I have aspx file which having upload file option.
<input type="file" name="Attachment" />
On submit button i am sending request to MVC controller to save file.
self.SaveVPD = function () {
var emp = { FirstName: 'edfd', SecondName: 'dfdf' };
var data = new VPDModel(emp, self.EvidenceForm());
var jsonData = ko.toJSON(data);
var url = pageUrl + '/Save';
debugger;
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8;",
//contentType: "multipart/form-data",
data: JSON.stringify(data),
//dataType: "json",
success: function (data) {
debugger;
if (data) {
//TODO::PP
}
else {
//TODO::PP
}
},
error: function () {
debugger;
//TODO::PP
}
});
}
My MVC controller is look like
[HttpPost]
public ActionResult Save(VPDModel vpdInfo) //, HttpPostedFileBase Attachment)
//public ActionResult Save(FormCollection collection)
{
if (ModelState.IsValid)
{
}
}
And my model is
public class VPDModel
{
public Employee Employee { get; set; }
public EvidenceForm EvidenceForm { get; set; }
}
EvedenceForm class is
public class EvidenceForm
{
//public string Attachment { get; set; }
public HttpPostedFileBase Attachment { get; set; }
}
When i send the request back to server VPDModel populate with all valid client side data without File Attachment. Its always null.
I have been to couple of article but cannot resolve it. can anyone help and let me know what am i doing wrong in it?
Related
I'm pretty new regarding frontend, and couldn't find a clear solution to this simple problem.
In a Visual 2017 c# ASP.NET Framework MVC project, for a single page with ONLY ONE SUBMIT button which is already used for updating some string of my model totalInfo, I want to update the integer property ModelltypeForView of my model from the selected value of n radiobuttons.
I learnt I could update my controller model going with an AJAX call, but I can't find the way to update my view model, I must miss something simple but not obvious for a beginner.
Here are the main parts of my MVC.
I am aware of the problems due to the return type of my SettModelltype of my controller, as well as the ajax and foreach loop of my view, so basically: how do I finish this code? Is this problem even fixable without any partial view?
Thank you so much for your time.
// Model TotalInfoModell.cs
public class TotalInfoModell
{
public List<Modelltype> Modelltyper { get; set; }
public int ModelltypeForView { get; set; }
}
public class Modelltype
{
public int MTIndex { get; set; }
public string MTName { get; set; }
public bool MTSelected { get; set; } //? useless?
}
// Controller MainController.cs
static TotalInfoModell _totalInfo;
[HttpGet]
public ActionResult Main()
{
if (_totalInfo == null)
{
_totalInfo = new TotalInfoModell();
}
return View(_totalInfo);
}
[HttpPost]
public ActionResult SettModelltype(TotalInfoModell totalInfoFraView)
{
_totalInfo.ModelltypeForView = totalInfoFraView.ModelltypeForView;
for (int i = 0; i < _totalInfo.Modelltyper.Count; i++)
{
_totalInfo.Modelltyper[i].MTSelected = (i == _totalInfo.ModelltypeForView);
} /// Could be useless
return RedirectToAction("Main"); //????
}
// View Main.cshtml
#foreach (var modelltype in Model.Modelltyper)
{
#Html.RadioButtonFor(i => modelltype.MTIndex == Model.ModelltypeForView, modelltype.MTIndex, new { #class = "MTSelected" }) // ????
#modelltype.MTName<br />
}
...
<script>
$(function () {
$('.MTSelected').change(function () {
var viewModel = {
"ModelltypeForView": $('.MTSelected:checked').val(),
};
$.ajax({
url: '#Url.Action("SettModelltype", "Main")',
data: viewModel,
type: 'POST',
success: function (data) {
},
error: function (xhr) {
alert("It didn't work");
}
}).done(function (data) {
alert("Done");
$('#Id').val(data.ModelltypeForView); //??? Should return totalInfoModell
});
});
});
</script>
I'm not sure I understand. Do you want to pass your viewmodel back with the redirect?
If that's the case you can add it as a parameter. Here is a post that can help
I want to post files and other data in one request using axios and asp.net mvc
javascript:
var otherData = {
Id: 123,
Name: "Sam"
};
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("files", files[i]);
}
// I have tried these cases
// case 1:
// formData.append("request", otherData);
// case 2:
// formData.append("Id", otherData.Id);
// formData.append("Name", otherData.Name);
axios.post("/../MyAction", formData, { headers: {"Content-Type": "multipart/form-data"} })
.then(...);
Action:
public ActionResult MyAction(IEnumerable<HttpPostedFileBase> files, MyModel request)
{
}
public class MyModel
{
public int Id {get; set;}
public string Name {get; set;}
}
The files received, but the other data not
How should I adjust my code to let it working?
By the way, can I let the HttpPostedFileBase in the model like:
public class MyModel
{
public int Id {get; set;}
public string Name {get; set;}
public IEnumerable<HttpPostedFileBase> Files {get; set;}
}
I am not sure what axios does. But with jQuery ajax api, you can send files and other values together using FormData over ajax.
$(function () {
$("#saveBtn").click(function(e) {
e.preventDefault();
var url = "#Url.Action("Create", "Home")";
var fdata = new FormData();
fdata.append("Id", 123);
fdata.append("Name", "Sam");
var fileInput = $('#Files')[0];
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
fdata.append("files", files[i]);
}
$.ajax({
type: 'post',
url: url,
data: fdata,
processData: false,
contentType: false
}).done(function(result) {
// do something with the result now
console.log(result);
});
});
});
And in your HttpPost action method, you can use the MyModel class as parameter type and model binder will be able to properly bind the posted data
[HttpPost]
public ActionResult Create(MyModel model)
{
// check model.Files & model.Id
// to do :Return something
}
I am using the Url.Action method to generate the correct relative path to the action method. It will work if this script code is inside a razor view. If this code is inside an external javascript file, follow the method described in this post.
I sent an object to controllers action thorugh ajax , but I don't know how to recevie the object in controller. My ajax call is :
$.ajax({
type: "POST",
url: '#Url.Action("Create","Home")',
data: { ID: '#Model.ID', Name: '#Model.Name'}
}).done(function (msg) {
alert("Added :" + msg);
});
This should work , BUt I can't figure out how to recevie the object in controller. I wrote this :
public ActionResult Create(Home h)
{
}
But it is not working . I neeed help in this , Thanks in advance.
My Home class :
public class Home
{
public int ID { get; set; }
public string Name { get; set; }
}
Your action should be like thus:
[HttpPost]
public ActionResult Create(Home h)
{
throw new NotImplementedException(); // put you code here
}
I am trying to send AJAX POST request to an MVC Application
$.ajax({
type: 'POST',
dataType: 'json',
data: {"FirstName":"chris","LastName":"cane"},
contentType: 'application/json',
url: "http://dev.irp.com/irp.Ajax.Search/home/Foo",
success: function (data) {
alert(data);
}
});
This script is present on a different server on an ASP.NET application. My MVC App to handle the code is as below
[HttpPost]
public JsonResult Foo(fromclient test)
{
var obj = new SearchMemberServiceClient();
var members = obj.FindMember(test.FirstName, test.LastName, "", "", "", "").Members;
IEnumerable<Bar> sorted =
from a in members
orderby a.FirstName ascending
group a by new
{
a.FormattedFullName,
a.MembershipsProxy[0].GoodFromDate,
a.MembershipsProxy[0].GoodThroughDate,
} into k
select new Bar
{
FormattedName = k.Key.FormattedFullName,
goodfrom = k.Key.GoodFromDate,
goodthru = k.Key.GoodThroughDate,
};
return Json(sorted.ToList());
}
public class Bar
{
public string FormattedName { get; set; }
public DateTime goodfrom { get; set; }
public DateTime goodthru { get; set; }
}
public class fromclient
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
The problem is the script needs to post to that url and get the json data. But as the controller does not have any view, When I look inside the console on the client side it says 404 error for the url and also it says XMLHttpRequest cannot load http://dev.irp.com/irp.Ajax.Search/home/Foo. Origin http://web-dev.irps.com is not allowed by Access-Control-Allow-Origin.
I dont know if the problem has to do with the absolute path of the url for ajax request. If so how could I overcome this?
Due to the same origin policy restriction that't built into browsers you cannot send AJAX requests to different domains. A possible workaround is to have the server return JSONP instead of JSON. Here's an example of a custom JsonpResult that you could use in your controller action.
Can U try JSONP ? Why json? It's perfect to cross-domain.
I've seen other posts on this subject and have fiddled with variations but still cannot not get the JSON model binding to work correctly.
I have the following in my global.asax.cs Application_Start method:
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
The post back data looks like this:
{"UserName":"Mike","Password":"password","Persist":true}
My PoCo:
public class UserLoginViewModel {
public string UserName { get; set; }
public string Password { get; set; }
public bool Persist { get; set; }
}
The controller method fires properly but has default UserLoginViewModel object with UserName = null, Password = null, and Persist = false; the signature looks like this:
[HttpPost]
public ActionResult Logon(UserLoginViewModel model) {
if (ModelState.IsValid) {
...
The problem is on the client side! I didn't have the contentType set.
$.ajax({
url: location.href,
type: "POST",
data: ko.toJSON(this),
datatype: "json",
**contentType: "application/json charset=utf-8",**
success: function (data) { alert("success"); },
error: function (data) { alert("error"); }
});