0

我正在尝试通过 API 而不是通常的<form action="http://www.mysite.com" method="post">.

API 接受一个 XML 字符串作为参数,例如:<Data><firstnamex>Hello</firstnamex><lastnamex>World</lastnamex></Data>.

我会这样做的 Web 表单中的旧方法是

String dataXml = "<Data>";
dataXml += "<firstnamex>" + firstnamex.Text + "</firstnamex>";
dataXml += "<lastnamex>" + lastnamex.Text + "</lastnamex>";
dataXml += "</Data>";

进而

mainApi.Service1 ws = new mainApi.Service1();
string retVal = ws.InsertRecord(dataXml);

由于我不能firstnamex.Text像在 Web 窗体中那样抓住控件,我该怎么做呢?

4

2 回答 2

1

您需要一个 ViewModel 来代表您在此“页面”上从用户那里收集的内容,以便完成调用。所以首先,创建一个 ViewModel 来保存这些东西。这个 ViewModel 还应该包含实际调用 DAL 的代码。让你的控制器太清楚需要对实际数据做什么是一个坏主意。只需让它知道在 ViewModel 上调用哪个方法,以及如何处理返回值(如果有)。

public class YourViewModel 
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // other fields here as needed.

    public YourViewModel() 
    {
        // you can put any field defaults you need here
    }

    public string InserRecord() 
    {
        String dataXml = "<Data>";
        dataXml += "<firstnamex>" + firstnamex.Text + "</firstnamex>";
        dataXml += "<lastnamex>" + lastnamex.Text + "</lastnamex>";
        dataXml += "</Data>";
        mainApi.Service1 ws = new mainApi.Service1();
        return ws.InsertRecord(dataXml);
    }
}

public class YourController 
{
    public ActionResult YourAction() 
    {
        var viewModel = new YourViewModel();
        return View(viewModel);
    }

    [HttpPost]
    public ActionResult YourAction(YourViewModel viewModel) 
    {
        var resultFromInsert = viewModel.InserRecord();
        // redirect here based on string returned above, or whatever.
    }
}

我喜欢我的模特胖;我的控制器瘦;我的观点完全迟钝。

于 2013-03-19T16:55:38.353 回答
0

它看起来像这样......

[HttpPost]
public ActionResult YourAction(YourModel model)
{
    String dataXml = "<Data>";
    dataXml += "<firstnamex>" + model.FirstName + "</firstnamex>";
    dataXml += "<lastnamex>" + model.LastName + "</lastnamex>";
    dataXml += "</Data>";

    // ...

    return View(model); // or redirect or whatever
}
于 2013-03-19T16:54:35.343 回答