Please help me!
My Controller can't recent Image File from angular.
Here my angular file
Here my Controller
Class Product:
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int Price { get; set; }
public byte[] Image { get; set; }
}
I try user HttpPostedFileBase in My Controller but not work.
Should I convert File to byte array before call Controller Function?
Take a look at these:
File Upload Using Angular JS and ASP.NET MVC 5
File Upload with Angular and ASP.NET MVC 4
If you're not uploading large images, you could also convert them to Base64 strings and post them to server.
Related
This is my Model and asp core functionality
public class RuleActionModel
{
public string RuleData { get; set; }
public string ActionData { get; set; }
}
[HttpPost]
public async Task<JsonResult> Create(string objectId, string applicationId, [FromBody]RuleActionModel ruleActionData)
{
string ruleData= ruleActionData.RuleData;
}
This is my angular code
var objectid="123";
var applicationid="1";
$scope.ruleActionData={};
ruleActionData.ruleData="{'name':'one'}";
ruleActionData.actionData="[{'name':'one'}]";
$scope.CreateRule = function () {
$http.post('/api/Rule/Create?objectId='+objectid+'&applicationId='+applicationid, $scope.ruleActionData).then(function (response) {
});
};
In the above code model not binding, but remaining query fields are bind.I tried with FromBody and without FromBody also. This code working in mvc with angularjs, but not in asp core. How to bind model properties from angularjs to asp core 2.1.
Try to use [FromQuery] attribute if you pass parameters in query string
I am new in c# and MVC and this is my question:
For my new website, I would like to have a DropDownList in my header so the visitors can choose a Currency.
I have a SQL server table named CurrencyList
I have a Controller named BaseController : Controller
I have a model:
public partial class CurrencyList
{
public int CurrencyId { get; set; }
public string CurrencyName { get; set; }
public string CurrencySymbol { get; set; }
public Nullable<decimal> CurrencyValue { get; set; }
public string Currency { get; set; }
public Nullable<System.DateTime> LastUpdate { get; set; }
}
Now, how do I get the datas in the select? And how do I manage the Post?
For my select, I will use only the field Currency, and by default EUR will be selected.
Onchange, I would like to save the Currency value in a session and/or cookie.
Thanks in advance.
You can use Ajax Get method to call the method of controller which get data for bind dropdown list
[HttpPost, Route("api/EtiketAPI/EtiketEkle/{makaleId}")]
public HttpResponseMessage EtiketEkle(string makaleId,Etiket[] values)
I have been recently using web api. I am stuck to bind an array which comes from web request and the request method is post method. Is there any way to bind data comes from request to my specified object ?
I am sending data with angularjs. Here is data form
[{"EtiketId":1,"EtiketAdi":"Microsoft","EtiketRadi":"microsoft","Makaleler":null},{"EtiketId":2,"EtiketAdi":".net","EtiketRadi":"-net","Makaleler":null}]
and my class
public class Etiket
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EtiketId { get; set; }
public string EtiketAdi { get; set; }
public string EtiketRadi { get; set; }
public virtual ICollection<Makale> Makaleler { get; set; }
}
here are you answers :
Sending binary data along with a REST API request
Processing binary data in Web API from a POST or PUT REST request
public partial class User
{
public System.Guid UserId { get; set; }
public Nullable<System.Guid> RoleId { get; set; }
public Nullable<long> MembershipNo { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Emaiil { get; set; }
public Nullable<decimal> MobileNo { get; set; }
public string Description { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual Role Role { get; set; }
}
This is my table in DB named Users which is associated with Roles table of DB (as you can see last virtual row at the end above)
Now My problem is simple. I'm using angulars $http.get() method to call my Web Api in MVC 4. When i call it, it gets connected and fetches desired record but it doesn't throw proper result back to .js file or controller.
At .js side I run into error. Every time, it executes .error(jsonResult,config,header,status) .
When I jump on to JsonResult, it shows me below error.
Object
ExceptionMessage: "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
ExceptionType: "System.InvalidOperationException"
InnerException: Object
ExceptionMessage: "Self referencing loop detected for property 'Role' with type
'System.Data.Entity.DynamicProxies.Role_82CA96EA045B1EB47E58B8FFD4472D86502EEA79837B4AE3AD705442F6236E58'.
Path 'Role.Users[0]'."
ExceptionType: "Newtonsoft.Json.JsonSerializationException"
Message: "An error has occurred."
I don't know what's wrong here. Is it json parsing error or something? if so, I've heard and read the articles that webapi in .net handles or throws json itself.
My call happens through
$http.get(apiUrl).success(function (jsonResult, header, config, status) {
debugger;
var number = parseInt(jsonResult.membershipNo) + 1;
$scope.membershipNo = "M" + number;
})
.error(function (jsonResult, header, config, status) {
debugger;
toastr.error('Something went wrong ! Contact Administrator!!!');
});
Edited:
One more thing to mention, .CS side when I fetch single cell value (from DB/table) , it gets returned back to .success() call but when i fetch particular row or all rows, it gets returned to .error() call. I'm using entity frameworkd 6.1.1. and above class is generated by EF-6.1.1.
public partial class Role
{
public Role()
{
this.Permissions = new List<Permission>();
this.Users = new List<User>();
}
public System.Guid RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual ICollection<Permission> Permissions { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Hi you can solve that in 2 easy steps
First Step: Create globalConfig class where you can set ignoring ReferenceLoopHandling (http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm) and if you crating js app you can set as well to remove xml formaters and always get return from Webapi as JSON string is usefull for debugging. So in your app_start folder add class GlobalConfig like below:
public class GlobalConfig
{
public static void CustomizeConfig(HttpConfiguration config)
{
// Remove Xml formatters. This means when we visit an endpoint from a browser,
// Instead of returning Xml, it will return Json.
//that is optional
config.Formatters.Remove(config.Formatters.XmlFormatter);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
}
Second Step: In Global.asax set your custom configuration to do that please add code below to method Application_Start():
GlobalConfig.CustomizeConfig(GlobalConfiguration.Configuration);
it sounds like:
the problem is that EF is using lazy loading that is not materialized in time of constructing this, on role. EF from early version has switched lazy loading on by default.
Suggested solution
Create subset of you user class, with the parts that you really need.
=> Its bad practise to fetch too much data that you are not gonna need.
I am beginning in this issue MVC 2 I hope you can help me. I created a basic model
public class RegisterModel
{
public string Name { get; set; }
public int idCountry { get; set; }
public string Country { get; set; }
}
And I have in the controller the following
public ActionResult Register()
ViewData["country"] = new SelectList(db.PAIS.ToList(), "ID_PAIS", "DESC_PAIS");
return View();
}
My view
<div class="editor-field">
<%= Html.DropDownList("country")%>
</div>
but when I want save on the data base show me a error
[HttpPost]
public ActionResult Register(RegisterModel model)
{
USUARIO usuario = new USUARIO()
{
name = model.name,
city = model.city // show me a error
}
}
Could you please tell me how to save in the data base from this parameters from dropdownlist in my aplication.
Please take a look at this question. I think it may help answer your question.