Programing

Razor View에서 POST 요청을받을 때 빈 문자열 대신 null이 표시되는 이유는 무엇입니까?

lottogame 2020. 11. 4. 07:38
반응형

Razor View에서 POST 요청을받을 때 빈 문자열 대신 null이 표시되는 이유는 무엇입니까?


값이 없을 때 빈 문자열을 수신했습니다.

[HttpPost]
public ActionResult Add(string text)
{
    // text is "" when there's no value provided by user
}

하지만 이제 나는 모델을 전달하고 있습니다

[HttpPost]
public ActionResult Add(SomeModel Model)
{
    // model.Text is null when there's no value provided by user
}

그래서 ?? ""연산자 를 사용해야합니다 .

왜 이런 일이 발생합니까?


DisplayFormat모델 클래스 속성에 속성을 사용할 수 있습니다 .

[DisplayFormat(ConvertEmptyStringToNull = false)]

기본 모델 바인딩은 새 SomeModel을 생성합니다. 문자열 유형의 기본값은 참조 유형이므로 null이므로 null로 설정됩니다.

이것은 string.IsNullOrEmpty () 메서드의 사용 사례입니까?


나는 Create and Edit에서 이것을 시도하고 있습니다 (내 개체는 'entity'라고 함) :-

        if (ModelState.IsValid)
        {
            RemoveStringNull(entity);
            db.Entity.Add(entity);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(entity);
    }

이것을 부르는 :-

    private void RemoveStringNull(object entity)
    {
        Type type = entity.GetType();
        FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
        for (int j = 0; j < fieldInfos.Length; j++)
        {
            FieldInfo propertyInfo = fieldInfos[j];
            if (propertyInfo.FieldType.Name == "String" )
            {
                object obj = propertyInfo.GetValue(entity);
                if(obj==null)
                    propertyInfo.SetValue(entity, "");
            }
        }
    }

Database First를 사용하고 모델 속성이 매번 지워지거나 다른 솔루션이 실패하는 경우 유용합니다.

참고 URL : https://stackoverflow.com/questions/3641723/why-do-i-get-null-instead-of-empty-string-when-receiving-post-request-in-from-ra

반응형