How to post a json object from to an mvc action - asp.net-mvc

I have a mvc action
[HttpPost]
public ActionResult EditUser(ApplicationUser model)
ApplicationUser class is:
public class ApplicationUser
{
public int UserId { get; set; }
[Required]
public string UserName { get; set; }
public byte[] HashedPassword { get; set; }
public bool IsActive { get; set; }
public bool IsVerified { get; set; }
}
In jquery side I am doing:
$.ajax({
method: 'POST',
url: '#Url.Content("~/UserAdmin/EditUser")',
dataType: "json",
data: ....How do I post the object...???
});
My question is how do I post the Json object to the method as I hit the break point but the object is null.

Use JSON.stringify to reliably convert your JS object to JSON data for sending across the wire
var user = {
UserId: '31750',
UserName: 'chugh97',
HashedPassword: '...',
IsActive: true,
IsVerified: true
};
...
dataType: 'json',
data: JSON.stringify(user),
...
Note - I would recommend making your HashedPassword a string type instead of a byte[], it would be easier to deal with that client-side.

Related

Ajax to C# controller: How to pass an Array of objects along with other data

I have the following code:
Class:
public class EngineGroup
{
public string CategoryName { get; set; }
public OemPart[] ArrOemParts { get; set; }
}
public class OemPart {
public string IdInDiagram { get; set; }
public string Sku { get; set; }
public string OemName { get; set; }
}
Controller:
public IActionResult Insert(EngineGroup eg){
}
JavaScript:
var formData = new FormData();
formData.append("CategoryName", groupEngineName);
formData.append("ArrOemParts", arrOemParts); // -- >>> this is an array of objects
$.ajax({
type: "POST",
data: formData,
url: "/Insert",
dataType: 'json',
contentType: false,
processData: false,
When I am sending the FormData to the controller, the array of objects is empty while the rest of the data is successfully passed to the controller.
I was trying to do JSON.stringify(formData) with no luck...
public class OemPart {
public string IdInDiagram { get; set; }
public string Sku { get; set; }
public string OemName { get; set; }
}
[HttpPost]
[IgnoreAntiforgeryToken(Order = 2000)]
public IActionResult InsertCategoryAndOemPart([FromBody] OemPart[] oemPart, string categoryName)
{
$.ajax({
type: "POST",
data: JSON.stringify(arrOemParts),
url: "/admin/engineGroup/InsertCategoryAndOemPart/?categoryName=" + categoryName
contentType: 'application/json; charset=utf-8'

pass a model from partial view to controller by ajax in mvc

My controller is
public ActionResult AddCustomer(Customer SM)
{
DataAccessLayer.ConClass obj = new DataAccessLayer.ConClass();
obj.SaveCustumerDetails(SM);
ModelState.Clear();
return PartialView();
}
my model is
public class Customer
{
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_id { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Contact_Person { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Contact_Person_Designation { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_name { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Address1 { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Address2 { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_City { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_State { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Country { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_PIN { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Phone1 { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Phone2 { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Email1 { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Email2 { get; set; }
}
Savecutomer is the name of the button .My partaial view code is
<script>
$('#SaveCustomer').click(
function () {
$.ajax({
type: "POST",
url: '#Url.Action("AddCustomer", "Customer")',
data: ' $("myform").serialize() ,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
complete: function (data) {
},
});
});
</script>
My need is to save customer details when i click on savecustomer button I don't want to see the details on url. In this way url holds data. I need to avoid it.
The method you have shown is a GET but its parameter is Customer SM which means that the DefaultModelBinder will generate a query string for each property in your model. I'm guessing that (because this method returns a partial view) your calling it in the main view using #Html.Action() or ajax to load a form into the view.
Firstly you need to methods, one GET and one POST
public ActionResult AddCustomer()
{
// Initialize a new instance of your model and pass it to the view
Customer model = new Customer();
return PartialView(model);
}
[HttpPost]
public JsonResult AddCustomer(Customer SM)
{
DataAccessLayer.ConClass obj = new DataAccessLayer.ConClass();
obj.SaveCustumerDetails(SM);
return Json(true); // see notes below
}
Note if you have included #Html.AntiForgeryToken in the partial, then your will also need to add [ValidateAntiForgeryToken]
Next, delete the script from your partial view and add it to the main view (scripts should never be in partials). Then change the script to
$('#SaveCustomer').click(function() {
$.ajax({
type: "POST",
url: '#Url.Action("AddCustomer", "Customer")',
data: $('#myform').serialize(), // change this to include the #
dataType: 'json',
success: function (data) {
// do something?
},
});
});
Note this assumes your form has id="myform". Note also contentType has been removed (its not required unless you stringify the data). It can also be simplified to
$.post('#Url.Action("AddCustomer", "Customer")', $('#myform').serialize(), function(data) {
// do something
});
Side notes: Its not clear what you want to do in the success callback. I would suggest that in the POST method you use return Json(true); if the save was successful, otherwise return a HTTP error code. Then in the success call back you might do something like
if (data) {
// the save was successful so reset existing form controls
$('#myform').get(0).reset();
// maybe display a message indicating success
}
and similarly you could handle an error by displaying a message indicating the the customer could not be saved.
When i changed to
$('#SaveCustomer').click(
function () {
$.ajax({
type: "POST",
url: '#Url.Action("AddCustomer", "Customer")',
data: "{'Customer_Name' : '" + $('#Customer_Name').val() + "' ," +
" 'Customer_Adress1' : '" + $('#Customer_Address1').val() + "'}" ,
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
})
and change controller to
public ActionResult AddCustomer(string Customer_Name, string Customer_Address1)
{
DataAccessLayer.ConClass obj = new DataAccessLayer.ConClass();
obj.SaveCustomerDetails( Customer_Name, Customer_Address1);
ModelState.Clear();
return PartialView();
}
it worksss

Receiving HTML-encoded values from asp.net mvc web api

I'm fairly new to MVC web api, and trying to get POST requests to process properly. It's mostly working, but string values are HTML-encoded. I thought this would be handled automatically, and I find no way to do this manually.
Here is the ajax request:
$.ajax({
url: '/api/PulseStudies/UpdateTask',
type: 'POST',
data: { 'userID': userid, 'taskID': CurExamTaskID, 'comment': comment, 'complete': complete },
async: true,
...
Here is the server-side API:
[HttpPost]
public HttpResponseMessage UpdateTask(TaskResponse value)
{
Tasks.UpdateTask(value.userID, value.taskID, value.comment, value.complete);
return Request.CreateResponse(HttpStatusCode.NoContent);
}
public class TaskResponse
{
public int userID { get; set; }
public long taskID { get; set; }
public string comment { get; set; }
public bool complete { get; set; }
}
The comment value is HTML-encoded, e.g., "blah%20blah". How do I get a properly decoded value?
I believe you mean it is UrlEncoded. On the server side you want HttpServerUtility.UrlDecode() http://msdn.microsoft.com/en-us/library/6196h3wt(v=vs.110).aspx to get it back.

View model absence in registration form

I have a partial view that contains a registration form with the following fields:
E-Mail
First Name
Last Name
Password
I am posting the form using jQuery Ajax without using View Model.
Question : Is it a good approach to not use View Model in his context ?
Question : Is my approach useless in case of unit test cases?
jQuery
$.ajax({
url: "#Url.Action("Action", "Controller", new { area = "Area" })",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({mail : "mails", nam : nam ......}),
traditional: true,
success: function (data) {
alert("wsaved");
}
});
[HpPost]
public Actionresult abc(string mail, string nam, sring lasnam)
{
return Json(new {succss = ru});
}
Is it a good approach to not use View Model in his context ?
No, it will make validation much harder. Suppose that you wanted to validate that the email is not empty and is indeed a valid email address. If you used a view model, all you had to do is decorate the Email property on your view model with the correct validation attributes. With your approach you will now have to write a couple of useless lines of code in your controller action for that.
Here's how your view model might look like:
public class RegisterUserViewModel
{
[Required]
[RegularExpression("PUT YOUR REGEX TO VALIDATE AN EMAIL HERE")]
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required]
[RegularExpression("PUT YOUR REGEX TO ENFORCE SOME PASSWORD STRENGTH")]
public string Password { get; set; }
}
and now your controller action becomes:
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
// validation failed
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new
{
Key = x.Key,
Errors = x.Value.Errors.Select(e => e.ErrorMessage)
}
);
return Json(new { success = false, errors = errors });
}
return Json(new { success = true });
}
IF you are using an ApiController with MVC 4, then you can use a Model to bind to, which will use (by default) Newton Json.NET.
ResponseModel
[DataContact]
public class ResponseModel
{
[DataMember]
public string Status { get; set; }
}
ActionModel
[DataContact]
public class RegisterUserViewModel
{
[Required]
[DataMember(isRequired=true)]
public string Email { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[Required]
[DataMember(isRequired="true")]
public string Password { get; set; }
}
ApiController Action
[HttpPost]
public ReponseModel Register(RegisterActionModel actionModel)
{
if (this.ModelState == valid)
{
//do stuff
return new ResponseModel()
{
Status = "OK"
};
}
else
{
return new ResponseModel()
{
Status = "Invalid Data"
}
}
}

Passing a knockout array of objects to an mvc controller action

Folks,
Can anyone help me or direct me to an example of a knockout viewmodel which contains an array of objects being passed to an asp.net mvc action? The only examples I have seen show just simple arrays of strings being passed.
Thanks
Here's an example from the official Knockout site. It's a Contacts editor build with nested arrays. [jsFiddle].
A fitting ASP.NET MVC Action could look like
public ActionResult SaveContacts(IEnumerable<Contact> contacts)
Where Contact is defined as the class:
public class Contact
{
public string firstName { get; set; }
public string lastName { get; set; }
public IEnumerable<Number> phones { get; set; }
}
Where Number is defined as the class:
public class Number
{
public string type { get; set; }
public string number { get; set; }
}
Given the JavaScript Knockout View Model from the example. Your save method could look like this
self.save = function() {
var jsonString = ko.mapping.toJSON(this.searchParams);
$.ajax({
url: "/MyController/SaveContacts",
data: jsonString,
type: 'POST',
contentType: 'application/json',
dataType: 'json'
});
};

Resources