简体   繁体   English

在Razor ASP.NET MVC中调用方法

[英]Calling a method in Razor ASP.NET MVC

I am a newbie at MVC and having trouble displaying the result of a certain method in a view input field. 我是MVC的新手,无法在视图输入字段中显示某种方法的结果。 I am not too sure if I am supposed to create the method in the cshtml or in a separate cs file. 我不太确定是否应该在cshtml或单独的cs文件中创建方法。

I have used the @function tag to create my method in a cshtml file below 我已经使用@function标记在下面的cshtml文件中创建我的方法

@functions{

    public int DaysCalc(DateTime first, DateTime second)
    {
        QuoteApp.Models.Quote ts = new QuoteApp.Models.Quote();
        ts.StartDate = first;
        ts.EndDate = second;

        int days;
        days = (second.Day - first.Day);
        return days;


    }

}

I am calling it this way in the cshtml file 我在cshtml文件中这样称呼它

 @Html.EditorFor(model =>model.DaysCalc(model.StartDate, model.EndDate), new { htmlAttributes = new { @class = "form-control", disabled = "disabled"} })

I get an error stating 我收到一个错误说明

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. 模板只能与字段访问,属性访问,一维数组索引或单参数自定义索引器表达式一起使用。

Description: An unhandled exception occurred during the execution of the current web request. 说明:执行当前Web请求期间发生未处理的异常。 Please review the stack trace for more information about the error and where it originated in the code. 请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。

Exception Details: System.InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. 异常详细信息:System.InvalidOperationException:模板只能与字段访问,属性访问,一维数组索引或单参数自定义索引器表达式一起使用。

Source Error: 源错误:

Line 63:             @Html.LabelFor(model => model.noOfDays, htmlAttributes: new { @class = "control-label col-md-2" })
Line 64:             <div class="col-md-10">
Line 65:                 @Html.EditorFor(model =>@DaysCalc(model.StartDate, model.EndDate),new { htmlAttributes = new { @class = "form-control", disabled = "disabled"} })
Line 66:                 @Html.ValidationMessageFor(model => model.noOfDays, "", new { @class = "text-danger" })
Line 67:             </div>

Source File:   Line: 65 

You can only use the For methods with actual properties on your model (ie not functions). 您只能在模型上使用具有实际属性的For方法(即不能使用函数)。 I'm not sure what you're actually trying to achieve by doing this, so I can't really help you further unless you update your question, but that explains your error at least. 我不确定这样做的目的是什么,因此除非您更新问题,否则我无法真正为您提供进一步的帮助,但这至少可以解释您的错误。

EDIT 编辑

First and foremost, I need to point out that your date calculation is not correct. 首先,我需要指出您的日期计算不正确。 What if StartDate is 2014-06-30 and EndDate is 2014-07-01. 如果StartDate为2014-06-30而EndDate为2014-07-01怎么办。 Then the result of is going to 1 - 30 = -29 . 然后,结果为1 - 30 = -29 I'm reasonably sure that's not what you're looking for. 我有理由确定这不是您要的东西。 There's a method on DateTime just for this purpose: DateTime上有一个方法专门用于此目的:

TimeSpan difference = EndDate.Subtract(StartDate);

The result is a TimeSpan , which you can then call difference.Days to get the number of days involved. 结果是TimeSpan ,您可以将其称为difference.Days以获取涉及的天数。 Also of note, there's a TotalDays property off TimeSpan that will return fractional days (whereas Days just returns whole days). 还要注意的是, TimeSpan上有一个TotalDays属性,该属性将返回小数天(而Days仅返回整天)。

Next, for what it's worth, and since you're new to all this, the in-view Razor helpers are a nice novelty, but they're impractical to the point of being useless, and frankly, they violate MVC (the pattern, not the framework from Microsoft). 接下来,就其价值而言,由于您不熟悉所有这些,因此,可视化的Razor帮助程序是一个很好的新颖性,但是它们变得无用到不切实际的地步,坦白地说,它们违反了MVC(而不是Microsoft的框架)。 If you need to do this type of calculation, the best place for it is on your model. 如果您需要进行这种类型的计算,那么最好的模型就是您的模型。 You can implement a property like: 您可以实现以下属性:

public int Days
{
    get
    {
        return EndDate.Subtract(StartDate).Days;
    }
}

However, that's read-only (there's no setter method), and if you're talking about using this as an input value, it doesn't make sense to have a read-only property backing it (unless, I guess, if you make it a read-only input, in which case it might as well just be plain-text). 但是,这是只读的(没有设置方法),如果您正在谈论将其用作输入值,那么拥有一个只读属性作为后盾是没有意义的(除非,我猜如果将其设为只读输入,在这种情况下,也可能只是纯文本)。 So, if this is something you intend to post back to you'll need to figure out what that means in terms of a setter. 因此,如果您打算将此内容发回给您,则需要弄清楚这对二传手而言意味着什么。 Honestly, I can't see what you would do with that because the only logical thing to do is have it set values for StartDate and EndDate , and you can't do that without some point of reference. 坦率地说,我看不到您会怎么做,因为唯一合乎逻辑的事情是让它设置StartDateEndDate值,并且没有参考点就无法做到。 You could require StartDate to be set, and then take a value for Days and then use that to calculate EndDate , but it all boils down to what your business requirements are. 您可能需要设置StartDate ,然后为Days取一个值,然后使用该值来计算EndDate ,但这全都归结为您的业务需求。

If you want to use EditorFor, create a property that returns your calculated value. 如果要使用EditorFor,请创建一个返回您的计算值的属性。

public class YourModel
{
    public int CalculatedDays
    {
        get
        {
            QuoteApp.Models.Quote ts = new QuoteApp.Models.Quote();
            ts.StartDate = first;
            ts.EndDate = second;

            return (ts.EndDate - ts.StartDate);
        }
    }
}

@Html.EditorFor(model => model.CalculatedDays, new { htmlAttributes = new { @class = "form-control", disabled = "disabled"} })

Add the Days property to your view model and store the result of the DaysCalc on it. 将Days属性添加到视图模型,并在其上存储DaysCalc的结果。

Then you can use it like: 然后您可以像这样使用它:

@Html.EditorFor(model =>model.Days, new { htmlAttributes = new { @class = "form-control", disabled = "disabled"} })

Try creating a property on your model (this is assuming you are using a typed model, not a dynamic one): 尝试在模型上创建一个属性(假设您使用的是类型化模型,而不是动态模型):

public int Days
{
    get {

        QuoteApp.Models.Quote ts = new QuoteApp.Models.Quote();
        ts.StartDate = StartDate;
        ts.EndDate = EndDate;

        int days;
        days = (EndDate.Day - StartDate.Day);
        return days;
    }
}

Usage: 用法:

@Html.EditorFor(model => model.Days, new { htmlAttributes = new { @class = "form-control", disabled = "disabled"} })

I'm not sure if EditorFor will work quite right with a readonly property or not, but it looks like you are just using it for display or some other purpose anyway? 我不确定EditorFor是否可以与readonly属性一起正常使用,但是您似乎只是将其用于显示或其他目的?

Also, I'm not sure what you are using the Quote object for, since it doesn't appear you are doing anything with it other than creating it, so this could be possibly simplified into: 另外,我不确定您使用Quote对象的目的是什么,因为除了创建它外,您似乎并没有对它做任何事情,因此可以简化为:

public int Days
{
    get {
        return EndDate.Day - StartDate.Day;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM