When I Post Back to My Controller All Values for My Model Are Null

When I post back to my controller all values for my model are null

The DefaultModelBinder does not set the value of fields, only properties. You need to change you model to include properties

public class LetterViewModel
{
public string LetterText { get; set; } // add getter/setter
}

ajax post to mvc controller, all values are null

When you want to pass json data to controller,you need to use [FromBody].

Here is a demo worked:

controller:

        [HttpGet]
public IActionResult UpdateOrder()
{
return View();
}
[HttpPost]
public ActionResult UpdateOrder([FromBody]Order order)
{

return new EmptyResult();
}

View:

@{
ViewData["Title"] = "UpdateOrder";
}

<h1>UpdateOrder</h1>
<button onclick="submit()">submit</button>
@section scripts{
<script type="text/javascript">
function submit() {
var orderUpdate = {};
orderUpdate.Id = 1;
orderUpdate.Responsible = "Responsible";
orderUpdate.Comments = "Comments";
var order = JSON.stringify(orderUpdate);
$.ajax({
type: "POST",
url: "/Test/UpdateOrder",
data: order,
contentType: "application/json; charset=utf-8",
});
}
</script>
}

Result:
Sample Image

All values are null when posting to controller in ASP.NET Core

It turns out the reason that it wasn't working is because the View only allows one form in it. I didn't know that it would only read the first form on my view, so problem solved. I had
<form asp-action="CreatePrescriber" asp-controller="Patients" method="Post"> and
<form asp-action="CreatePrescription" asp-controller="Patients" method="Post">. It would take one <form /> and stop reading after that.

ViewModel data is all null when passed to my controller?

This kind of stuff makes me so frustrated when learning new architecture but I've figured it out. It is a naming convention issue. I've addressed the issue and it is now working properly:

The conflicting names were:

public string Model { get; set; }

from my ViewModel, and:

public async Task<IActionResult> NewResource(AddResourceViewModel model)

from my controller. So the Model is conflicting with the model...

According to: http://ideasof.andersaberg.com/development/aspnet-mvc-4-model-binding-null-on-post

Do not name your incoming variables in the Action the same as you do in the model being posted. That will mess up the Model Binder.

Model always NULL when POST from View to Controller

Properties in the model should be defined as auto property.

public class Partner
{
public Guid ID {get; set;}
public string Type {get; set;}
public string Code {get; set;}
public string Name {get; set;}
public string IDCard {get; set;}
public DateTime BirthDate {get; set;}
public bool CardStatus {get; set;}
public string Address {get; set;}
public string Email {get; set;}
}


Related Topics



Leave a reply



Submit