How to omit / prohibit sending data to the POST method in the controller in MVC

I have a view that the model uses, and I use this information to create the form. I have three form steps that are optional or may not be displayed.

The problem is that these hidden sections are published along with the form data and violate the business logic. (I do not control business logic)

So, is there a way to tell the structure not to pass specific sections or fields? Perhaps a VIA class or something else?

I know that I can use AJAX to send specific sections as needed, but the site specification should be hidden and displayed as needed.

+4
source share
2 answers

Show / Hide does not enable / disable sending the value to Controller.

Items or simply not editable will be returned (in 99% of cases) as / . DisablednullminVal

You can set the elements in the view as Disabledusing JQueryin the script:

$('#elementID').attr("disabled", true);

OR you can use the command DOM:

document.getElementById('elementID').disabled = "true";

Thus, you can set the fields as DisabledANDHidden , so that it is not displayed or populated . Then in Controlleryou can simply base your business logic on whether or not certain fields (preferred mandatory fields, if any) are null.


C# : string:

if (string.IsNullOrWhiteSpace(Model.stringField))
{
    ModelState.AddModelError("stringField", "This is an error.");
}

DateTime:

if (Model.dateTimeField == DateTime.MinValue)
{
    ModelState.AddModelError("dateTimeField ", "This is an error.");
}

, / JQuery:

$('#elementID').hide();
$('#elementID').show();
+1

, / .

6 ASP.NET MVC.

:

:

[HttpPost]
public ViewResult Edit([Bind(Include = "FirstName")] User user)
{
  // ...
}

:

[HttpPost]
public ViewResult Edit([Bind(Exclude = "IsAdmin")] User user)
{
  // ...
}

TryUpdateModel()

[HttpPost]
public ViewResult Edit()
{
  var user = new User();
  TryUpdateModel(user, includeProperties: new[] { "FirstName" });
  // ...
}

public interface IUserInputModel
{
  string FirstName { get; set; }
}

public class User : IUserInputModel
{
  public string FirstName { get; set; }
  public bool IsAdmin { get; set; }
}

[HttpPost]
public ViewResult Edit()
{
  var user = new User();
  TryUpdateModel<IUserInputModel>(user);
  // ...
}

ReadOnlyAttribute

public class User 
{
  public string FirstName { get; set; }

  [ReadOnly(true)]
  public bool IsAdmin { get; set; }
}

, ViewModel, :

public class UserInputViewModel
{
  public string FirstName { get; set; }
}
+1

Source: https://habr.com/ru/post/1547753/


All Articles