English 中文(简体)
在MVC视图中从模型属性值中删除空白的简洁方法
原标题:Succinct way to remove whitespace from model property values in MVC view

我使用MVC,在我的视图中,我使用视图模型中某些属性的值将类分配给各种div等。

但是,这些值包含空格,我需要在呈现HTML之前删除这些空格。

还有别的办法吗?

<% Response.Write(benefit.Name.Replace(" ","")); %>
问题回答

仔细想想,视图中的代码只是在编辑一个字符串。所以一个基本的替换,正如你所做的,我会怎么做。

但是,为什么不在您的模型中进行工作(即提供返回修剪字符串的属性)?或者更好的是,一种方法?例如:

<%: Model.ReplaceWS(benefit.Name); %>

其中:

public string ReplaceWS(string s)
{
   s = s.Replace(" ", "");
   return s;
}

如果没有别的,这看起来更整洁,使视图更容易阅读。

您还可以为字符串创建一个扩展方法(您可以通过在扩展方法定义中使用给定的命名空间来限制可见性)

这样你就可以写:

<%: benefit.Name.ReplaceWS(); %>

我认为这是我的首选,因为它表达了你正在做的事情

使用字符串的Replace方法是可以的。另一种选择是使用Regex,但这更复杂。

但是,您不应该真正使用Response.Write在ASP.NET MVC模板中-有一个输出分隔符标记<;%:为此:

<%: benefit.Name.Replace(" ","") %>

请注意,使用<;%:标签

这不是更简洁了吗?

注意:您应该使用<;%=在MVC 1中,并且<;%:在MVC 2中。后者对字符串进行消毒以防止XSS攻击。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签