PDA

View Full Version : سوال: تبدیل EditorFor به Lable



Iran58
سه شنبه 14 فروردین 1397, 13:18 عصر
سلام
من کد زیر را دارم

<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control",disabled = "disabled" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>

حال می خواهم جای EditorFor بتوانم از چیزی مانند LabelFor اتسفاده کنم که فقط خواندی باشد
درضمن از

disabled = "disabled"

نمی خواهم استفاده کنم چون کاربر می تواند تغییر بدهد

Moien Tajik
سه شنبه 14 فروردین 1397, 14:49 عصر
اگر میخواید سمت اکشن هم اصلا قابل دریافت نباشه ، میتونید از Bind-Exclude استفاده کنید.
اما اگر میخواید سمت اکشن دریافت بشه ، اما در ویو قابل تغییر توسط کاربر نباشه ، میتونید از همچین چیزی استفاده کنید :

HTML Helper :

public static class HtmlExtensions
{
public static MvcHtmlString SecureHidden(this HtmlHelper htmlHelper, string name, object value)
{
return SecureHidden(htmlHelper, name, value, null);
}

public static MvcHtmlString SecureHidden(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
{
return SecureHidden(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAtt ributes));
}

private static MvcHtmlString SecureHidden(
this HtmlHelper htmlHelper,
string name,
object value = null,
IDictionary<string, object> htmlAttributes = null)
{
return SecureHiddenHelper(htmlHelper, value: value, name: name, htmlAttributes: htmlAttributes);
}

public static MvcHtmlString SecureHiddenFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes)
{
return SecureHiddenFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAtt ributes));
}

public static MvcHtmlString SecureHiddenFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IDictionary<string, object> htmlAttributes = null)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

return SecureHiddenHelper(htmlHelper, metadata.Model, ExpressionHelper.GetExpressionText(expression), htmlAttributes);
}

public static MvcHtmlString DisableIf(this MvcHtmlString instance, Func<bool> expression)
{
const string disabled = ""disabled"";

if (!expression.Invoke()) return instance;

var html = instance.ToString();
html = html.Insert(html.IndexOf(">", StringComparison.Ordinal), " disabled= " + disabled);

return new MvcHtmlString(html);
}

private static MvcHtmlString SecureHiddenHelper(HtmlHelper htmlHelper,
object value,
string name,
IDictionary<string, object> htmlAttributes)
{
var binaryValue = value as Binary;

if (binaryValue != null)
value = binaryValue.ToArray();

if (value is byte[] byteArrayValue)
value = Convert.ToBase64String(byteArrayValue);

return InputHelper(htmlHelper, name, value, setId: true, format: null, htmlAttributes: htmlAttributes);
}

private static MvcHtmlString InputHelper(HtmlHelper htmlHelper,
string name,
object value,
bool setId,
string format,
IDictionary<string, object> htmlAttributes)
{
var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFu llHtmlFieldName(name);

if (string.IsNullOrEmpty(fullName))
throw new ArgumentException("name");

var inputItemBuilder = new StringBuilder();

var hiddenInput = new TagBuilder("input");
hiddenInput.MergeAttributes(htmlAttributes);
hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));
hiddenInput.MergeAttribute("name", fullName, true);
hiddenInput.MergeAttribute("value", htmlHelper.FormatValue(value, format));

var hiddenInputHash = new TagBuilder("input");
hiddenInputHash.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));
hiddenInputHash.MergeAttribute("name", $"__{fullName}Token", true);

var identity = htmlHelper.ViewContext.HttpContext.User.Identity;

if (!string.IsNullOrEmpty(identity.Name))
value = $"{identity.Name}_{value}";

var encodedValue = Encoding.Unicode.GetBytes(htmlHelper.FormatValue(v alue, format));

hiddenInputHash.MergeAttribute(
"value",
Convert.ToBase64String(MachineKey.Protect(encodedV alue, "Protected Hidden Input Token")));

if (setId)
{
hiddenInput.GenerateId(fullName);
hiddenInputHash.GenerateId($"__{fullName}Token");
}

inputItemBuilder.Append(hiddenInput.ToString(TagRe nderMode.SelfClosing));
inputItemBuilder.Append(hiddenInputHash.ToString(T agRenderMode.SelfClosing));

return MvcHtmlString.Create(inputItemBuilder.ToString());
}
}


Validate Attribute :

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class ValidateSecureInputAttribute : FilterAttribute, IAuthorizationFilter
{
private readonly string[] _properties;

public ValidateSecureInputAttribute(params string[] properties)
{
if (properties == null || !properties.Any())
throw new ArgumentException("Secure inputs are not specified !");

_properties = properties;
}

public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException(nameof(filterContext));
}

_properties.ToList().ForEach(property => Validate(filterContext, property));
}

private static void Validate(AuthorizationContext filterContext, string property)
{
var protectedValue = filterContext.HttpContext.Request.Form[$"__{property}Token"];
var decodedValue = Convert.FromBase64String(protectedValue);

var decryptedValue = MachineKey.Unprotect(decodedValue, "Protected Hidden Input Token");

if (decryptedValue == null)
{
throw new HttpSecureHiddenInputException("A required security token was not supplied or was invalid.");
}

protectedValue = Encoding.Unicode.GetString(decryptedValue);

var originalValue = filterContext.HttpContext.Request.Form[property];

var identity = filterContext.HttpContext.User.Identity;

if (!string.IsNullOrEmpty(identity.Name))
originalValue = $"{identity.Name}_{originalValue}";

if (!protectedValue.Equals(originalValue))
throw new HttpSecureHiddenInputException("A required security token was not supplied or was invalid.");
}
}


بعد از اینکه این 2 کلاس رو اضافه کردید ، میتونید به این شکل استفاده کنید :

View :

@Html.SecureHiddenFor(model => model.ID)


Controller :

[HttpPost]
[ValidateAntiForgeryToken]
[ValidateSecureInput(nameof(Product.ID))]
public async Task<ActionResult> Edit(Product product)
{
// ...
}